Fewest Swaps to Bring an Array with Duplicates into Sorted Order
Arrays & HashingModel answerLast 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 lengthn.
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
nums | Sorted form | Answer | Reasoning |
|---|---|---|---|
[2, 1, 2] | [1, 2, 2] | 1 | Swap indices 0 and 1. |
[1, 5, 1, 5] | [1, 1, 5, 5] | 1 | One 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Core insight: think in values, not indices
The standard duplicate-free approach assigns each element its unique target index, reads off the resulting permutation, and counts n − (number of cycles) swaps. With duplicates this breaks down because identical values can legally land in any of their target slots, giving many possible permutations. Picking the wrong one inflates the cycle count.
Classic shortcut that fails: stable-sort by (value, original_index) to pin down a unique mapping, then count cycles. Counterexample:
nums = [1, 2, 2, 1] sorted = [1, 1, 2, 2]
stable mapping: index 0→0, index 3→1, index 1→2, index 2→3
Cycles: (0)(1 3 2) — two cycles → 4 − 2 = 2 swaps
Actual optimum: swap index 1 and index 3 → 1 swap
The stable mapping needlessly chained indices 1, 2, and 3 into one long cycle.
The value-graph model
Let s = sorted(nums). For every position i where nums[i] != s[i], add a directed edge s[i] → nums[i]: "this slot is owed s[i] but currently holds nums[i]." Because every value appears the same number of times in nums and s, each node's in-degree equals its out-degree — the graph decomposes into edge-disjoint directed cycles.
A cycle of length L requires L − 1 swaps. So:
total swaps = (mismatched positions) − (number of cycles)
Minimizing swaps means maximizing the number of cycles, which means preferring short cycles.
Greedy 2-cycle cancellation
A 2-cycle exists when edges a → b and b → a are both present (two slots that hold each other's needed value). One swap fixes both — the best possible ratio. Cancelling all available 2-cycle pairs first is provably optimal: any solution that skips a 2-cycle in favor of merging its edges into longer cycles cannot do better.
Cancel min(count[a→b], count[b→a]) pairs for every unordered value pair {a, b}.
General case and NP-hardness caveat
After 2-cycle cancellation, every remaining edge pair (a→b, b→a) is fully consumed, so all edges between any two vertices run in one direction only. Maximizing cycles in the remaining Eulerian digraph is equivalent to the minimum interchange rearrangement of strings problem, which is NP-hard in general. A candidate should state this clearly rather than claiming false optimality.
For inputs with at most three distinct mismatched values, all remaining cycles have length exactly 3, so the greedy gives the exact answer. In practice, further greedily collapsing 3-cycles before a general walk is a useful extension worth mentioning.
The walk-based decomposition below is not globally optimal for arbitrary large alphabets, but it is correct (never an underestimate), efficient, and exact on small alphabets and on all common interview inputs.
Walking the remainder into cycles
After 2-cycle cancellation, walk unused edges while maintaining the current path and a vertex → path-position map. Whenever the walk arrives at a vertex already on the path, a simple cycle has closed: record cycle_length − 1 swaps and pop those vertices. Because the graph is balanced, every vertex entered via an edge still has an unused outgoing edge, so the walk never gets stuck.
Complexity
- Time:
O(n log n)dominated by sorting. Building edge counts, cancelling 2-cycles, and the walk are allO(n)expected (total edge count ≤n). - Space:
O(n)for the sorted copy, counters, and adjacency lists.
Python implementation
from collections import Counter, defaultdict
from typing import List
def fewest_swaps_to_sort(nums: List[int]) -> int:
s = sorted(nums)
# Build edge multiset: (needed_value, current_value) for each mismatched slot.
cnt = Counter()
for needed, have in zip(s, nums):
if needed != have:
cnt[(needed, have)] += 1
swaps = 0
# Step 1: cancel 2-cycles greedily.
# Each cancelled pair fixes two slots in one swap.
for (a, b) in list(cnt.keys()):
if a < b and (b, a) in cnt:
k = min(cnt[(a, b)], cnt[(b, a)])
if k:
swaps += k
cnt[(a, b)] -= k
cnt[(b, a)] -= k
# Step 2: build adjacency lists from surviving edges.
adj = defaultdict(list)
for (a, b), c in cnt.items():
if c > 0:
adj[a].extend([b] * c)
# Step 3: decompose the balanced remainder into simple cycles.
for start in list(adj.keys()):
if not adj[start]:
continue
path = [start]
pos = {start: 0} # vertex -> index in path
while True:
u = path[-1]
if not adj[u]:
break # only reachable once the path collapses back to start
w = adj[u].pop()
if w in pos:
# Close a simple cycle from pos[w] to the current end.
cycle_len = len(path) - pos[w]
swaps += cycle_len - 1
for v in path[pos[w] + 1:]:
del pos[v]
del path[pos[w] + 1:]
else:
pos[w] = len(path)
path.append(w)
return swaps
Verifying the examples
[2, 1, 2]→ edges:1→2,2→1. One 2-cycle pair. Answer: 1. ✓[1, 5, 1, 5]→ edges:1→5,5→1. One 2-cycle pair. Answer: 1. ✓[1, 2, 2, 1](the counterexample) → edges:1→2,2→1. One 2-cycle pair. Answer: 1 (correct; the stable-sort index method gives 2). ✓
Edge cases
- Already sorted or all elements equal: no mismatched positions, answer
0. n = 1: trivially0.- Only two distinct mismatched values: all edges pair into 2-cycles, answer is
(mismatched positions) / 2. - Negative or very large values: they serve only as dictionary keys, so no coordinate compression is needed.
- Heavy multiplicity on a single edge (e.g.
[2,2,2,1,1,1]): the counter handles this correctly; do not flatten to a set.
What a strong answer covers
- Identifies the failure mode of index-based stable mapping with a concrete counterexample.
- Reframes the problem as a value graph and derives
swaps = mismatches − cycles. - Justifies greedy 2-cycle cancellation and acknowledges NP-hardness of the fully general case without abandoning the practical solution.
- Delivers clean
O(n log n)code and correctly handles all edge cases.