Problem 373931 · medium · Level 03 Linear Management & Searching

Swapping Library Books Into Order

sorting · permutations · cycle decomposition

A shelf holds books whose catalogue numbers nums are all different. The librarian may lift any two books, wherever they stand (not only neighbours), and swap their places. Return the fewest swaps that leave the catalogue numbers in ascending order.

Examples

Input:  nums = [9, 4, 1, 6]
Output: 2
Explanation: Swap 9 with 1, giving [1, 4, 9, 6], then swap 9 with 6.
Input:  nums = [5, 8, 9, 3]
Output: 3

Constraints

  • 0 <= len(nums) <= 10**5, all values distinct
  • Target complexity: O(n log n).

Goals

  • Map each element to the position it must end up in
  • Find the cycles of that mapping
  • Convert cycle lengths into a swap count
Starting Python…