We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all 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)