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.
intcountSwaps(vector<int>arr,vector<int>sortedArr){intn=arr.size();unordered_map<int,int>indexMap;// Mapping each value to its index in the sorted arrayfor(inti=0;i<n;i++)indexMap[sortedArr[i]]=i;vector<bool>visited(n,false);intswaps=0;for(inti=0;i<n;i++){// If already visited or already in the correct position, skipif(visited[i]||indexMap[arr[i]]==i)continue;// Cycle detectionintcycleSize=0;intj=i;while(!visited[j]){visited[j]=true;j=indexMap[arr[j]];cycleSize++;}// A cycle of size k requires (k-1) swapsif(cycleSize>1)swaps+=(cycleSize-1);}intlilysHomework(vector<int>arr){vector<int>sortedArr=arr;// Sort in ascending order and count swapssort(sortedArr.begin(),sortedArr.end());intswapsAsc=countSwaps(arr,sortedArr);// Sort in descending order and count swapssort(sortedArr.begin(),sortedArr.end(),greater<int>());intswapsDesc=countSwaps(arr,sortedArr);// Return minimum of the tworeturnmin(swapsAsc,swapsDesc);}returnswaps;}
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 →