KatInterview

Fewest Swaps to Bring an Array with Duplicates into Sorted Order

Arrays & HashingModel answer
HardModel answerArrays & Hashingsortingpermutationscycle-detection

Last updated

Given an integer array that may contain duplicates, find the minimum number of arbitrary index swaps needed to sort it in non-decreasing order.

Problem

You have an integer array nums of length n. In a single operation you may pick any two indices i and j and exchange the values at those positions.

Return the smallest number of such operations needed to leave nums in non-decreasing order.

Input

  • nums: an integer array of length n.

Output

A single integer: the fewest swaps required.

Constraints

  • 1 <= n <= 2 * 10^5
  • -10^9 <= nums[i] <= 10^9

Important note on duplicates

Because the array may contain repeated values, there are often several valid ways to reach the sorted result (e.g. two equal elements can occupy each other's target positions interchangeably). Your answer must reflect the minimum over all valid sorted targets, not just one arbitrarily chosen assignment.

Examples

numsSorted formAnswerReasoning
[2, 1, 2][1, 2, 2]1Swap indices 0 and 1.
[1, 5, 1, 5][1, 1, 5, 5]1One swap brings the array to [1, 1, 5, 5].

What is expected

Explain your reasoning, identify any well-known approaches that fail and why, describe an O(n log n) strategy, and provide a working implementation. Discuss time and space complexity and any relevant edge cases.

Hints

Hint 1

Start by asking what 'sorted target' each element should map to. With no duplicates the answer is unique, but with duplicates the same sorted value can fill any of its target slots — choosing the assignment wisely is where the savings come from.

Hint 2

Instead of reasoning about index assignments, try building a graph on values: for every mismatched position, draw a directed edge from the value that slot needs to the value it currently holds. What does the structure of this graph tell you about the number of swaps?

Hint 3

In a directed graph where every vertex has equal in-degree and out-degree (Eulerian), a cycle of length L can be resolved in L − 1 swaps. Fixing 2-cycles first (two values swapped with each other) is greedy-optimal. After handling 2-cycles, think about whether a perfectly optimal decomposition of longer cycles is tractable in general.