leeway00 / CodingTestPractice

0 stars 0 forks source link

minimumSwaps #1

Open leeway00 opened 2 years ago

leeway00 commented 2 years ago

def minimumSwaps(arr):
    n = len(arr)
    arrpos = [*enumerate(arr)]
    arrpos.sort(key = lambda it : it[1])
    vis = {k : False for k in range(n)}

    ans = 0
    for i in range(n):
        if vis[i] or arrpos[i][0] == i:
            continue
        cycle_size = 0
        j = i # j finds local cycle starting from i
        while not vis[j]: # finding cycle
            vis[j] = True # mark True when j is included in the cycle
            j = arrpos[j][0] # update j to the next position in the cycle
            cycle_size += 1 # increment cycle size
        if cycle_size > 0:
            ans += (cycle_size - 1)
    return ans

minimumSwaps(a)
leeway00 commented 2 years ago
    res = 0
    arrtemp = sorted([*enumerate(arr)], key = lambda x: x[1])
    circit = {k: False for k in range(len(arr))}

    for ind, val in arrtemp: #sorted based on val
        if ind+1 != val and not circit[ind]:
            start = ind
            cycle = 0
            while not circit[start]:
                circit[start] = True
                start = arrtemp[start][0]
                cycle +=1
            res += cycle -1
    return res
leeway00 commented 2 years ago

def minimumSwaps(arr):
    n = len(arr)
    ans = 0
    temp = arr.copy()
    temp.sort() # [1,2,3,4,5]
    h = {val: ind for ind, val in enumerate(arr)}

    init = 0 
    for i in range(n):
        if (arr[i] != temp[i]):
            ans += 1
            init = arr[i]
            arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i]
            h[init] = h[temp[i]]
            h[temp[i]] = i

    return ans