[DAY2]Minimum Swaps 2

Sherlock Chiou
1 min readOct 14, 2019

--

https://www.hackerrank.com/challen…/minimum-swaps-2/problem…

Solution 1: Use Greedy Method to swap each number in ascending order. But this approach needs to traverse the whole array when an element is swapped. The reason why we need to traverse the whole array is to find the position with corresponding value. Time complexity would be O(N²).

Solution 2: We can continuously swap elements until forming a cycle. For each number in the array, we need to record if the element was swapped. First, we need to check if the element is swapped to right position. And we check if this element is in the right position. If not, we start to swap until a cycle is formed.python

--

--

Sherlock Chiou
Sherlock Chiou

Written by Sherlock Chiou

Be Effective and Optimize for Learning

No responses yet