Lily's Homework

  • + 0 comments

    I try to find cycles by comparing the list to sorted array. i check forwards and backwards and find which one has the min. O(n log n) space, 0(n) space ` def lilysHomework(arr): # Write your code here sorted_arr = arr.copy() sorted_arr.sort() arr_map = {v: k for k, v in enumerate(sorted_arr)} visited = [0] * len(arr)

    swaps = 0
    r_swaps = 0
    # print(arr_map)
    for i in range(len(arr)):
        if arr[i] != sorted_arr[i]:
            k = i
            if not visited[k]:
                swaps -= 1
            while not visited[k]:
                # print("visiting", k)
                visited[k] = 1
                k = arr_map[arr[k]]
                swaps += 1
    
    sorted_arr.reverse()
    arr_map = {v: k for k, v in enumerate(sorted_arr)}
    visited = [0] * len(arr)
    
    for i in range(len(arr)):
        if arr[i] != sorted_arr[i]:
            k = i
            if not visited[k]:
                r_swaps -= 1
            while not visited[k]:
                # print("r visiting", k)
                visited[k] = 1
                k = arr_map[arr[k]]
                r_swaps += 1
    
    return min(swaps, r_swaps)