
The simplest way to complete this challenge would be to get the minimum of every unsorted part, and swap it to its correct position and increase the sorted part accordingly until the whole array is sorted. This gives you the correct answer but does not give you the answer as fast as HackerRank wants. The brute-force algorithm would give you a Time Exceeded error in HackerRank.
So, a smarter, and faster approach to this problem is as follows.(P.S. something like a linked list)
In the first part of the code ( up to line 27) we get the minimum of the whole array and put it in the first position of the array while increasing swaps by one. This will be our base.
Then, as we know that the problems consists of consecutive integers, we can calculate the exact position of any number in the list after we calculate the minimum of the list. Then swap accordingly and increase the count and finally return it.
// it works as followsSay for example the list contains 6 7 8 5 9After we do the first part we have 5 7 8 6 9 with swaps = 1Then we iterate through the remaining list and:
Now we have 7 which is supposed to be at 7-5 = 2nd position in the array. Thus, we swap them which gives 5 8 7 6 9. Now we hold on to 8 and repeat the same for 8. This means, 8’s actual position is 8-5 = 3rd. So we swap it and do the same for the other swapped number. Once all the positions are checked and swapped in this way, the remaining are checked iteratively followed by the while loop swapping again if the conditions are met. It works like a linked list in some way.

Here is the video explaining it in detail. (UPDATED)
Thank you!