Skip to content
Advertisement

Min swaps for sorting list of consecutive integers

The problem:

You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the minimum number of swaps required to sort the array in ascending order.

My solution/issue:

My code does what it is supposed to; however, for large arrays it takes longer to run than allowed.

JavaScript

Any ideas/advice on how could I optimize this?

Advertisement

Answer

Since the list.index method costs O(n) in time complexity, calling it in a loop over the length of the list would result in O(n ^ 2) time complexity.

You can instead map the numbers in the list to their respective indices as a dict, so that the lookup of a number’s index would cost O(1) on average, resulting in an overall time complexity of O(n) instead. Update the indices accordingly whenever a swap is performed:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement