Problem 373931 · medium · Phase 03 Linear Management & Searching

Minimum Swaps to Sort

sorting · permutations · cycle decomposition

Given a list of distinct integers nums, return the minimum number of swaps (of any two positions, not necessarily adjacent) needed to sort it in ascending order.

Examples

Input:  nums = [4, 3, 2, 1]
Output: 2
Explanation: Swap 4 with 1, then 3 with 2.
Input:  nums = [2, 3, 4, 1]
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…