Amazon Online Assessment (OA) 2021 - Number of Swaps to Sort | HackerRank

Here's a basic scenario: we have a list of numbers and a specific way to sort these numbers by exchanging their places, or in other words, swapping them. The task at hand is to find out how many such swaps would be necessary to put the entire list in order.

Example 1:

Input: [5, 4, 1, 2]

Output: 5

Explanation:

  • Swap index 0 with 1 to form the sorted array [4, 5, 1, 2].
  • Swap index 0 with 2 to form the sorted array [1, 5, 4, 2].
  • Swap index 1 with 2 to form the sorted array [1, 4, 5, 2].
  • Swap index 1 with 3 to form the sorted array [1, 2, 5, 4].
  • Swap index 2 with 3 to form the sorted array [1, 2, 4, 5].

Solution

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ