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.
defnum_of_swaps(arr):"""Calculates min swaps to sort an array."""# Create a dictionary to store the original indices of elementsori_idx={val:ifori,valinenumerate(arr)}# Sort the array and store the sorted versionsorted_arr=sorted(arr)swap_num=0#Initializeswapcounter# Iterate over the arrayforiinrange(len(arr)):# If the element is out of placeifarr[i]!=sorted_arr[i]:# Find the index of the corresponding element in the original arrayj=ori_idx[sorted_arr[i]]# Swap the elementsarr[i],arr[j]=arr[j],arr[i]# Update the indices in the ori_idx dictionaryori_idx[arr[i]],ori_idx[arr[j]]=i,jswap_num+=1#Incrementswapcounterreturnswap_num#ReturntotalswapsdeflilysHomework(arr):"""Calculates min swaps for ascending/descending sort."""# Calculate the minimum number of swaps needed for both ascending and descending ordersreturnmin(num_of_swaps(arr[:]),num_of_swaps(arr[::-1]))
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 →