Smallest String With Swaps
Difficulty: Medium · Pattern: Union-Find · LeetCode #1202
pairs[i] = [a, b] lets you swap s[a] and s[b] any number of times. Return the lexicographically smallest string you can reach.
Examples
text
s = "dcab", pairs = [[0,3],[1,2]] → "bacd"
s = "dcab", pairs = [[0,3],[1,2],[0,2]] → "abcd"
s = "cba", pairs = [[0,1],[1,2]] → "abc"Hints
- If i↔j and j↔k are swappable, the characters at i, j and k can be arranged in any order (adjacent transpositions generate all permutations).
- So find the connected components of indices, and within each, place the sorted characters into the sorted indices.
Approach
- Union-Find over the indices using
pairs. - Group the indices by root. Each group's index list is already increasing if you add indices in order.
- For each group, sort its characters and write them back into its (increasing) indices.
That's O(n log n + P · α(n)). The general principle: arbitrary swaps along a connected graph = arbitrary permutations within each component.
Complexity
Time: O(n log n + P · α(n)). Space: O(n).
Python solution
from collections import defaultdict
def smallestStringWithSwaps(s, pairs):
parent = list(range(len(s)))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in pairs:
parent[find(a)] = find(b)
groups = defaultdict(list)
for i in range(len(s)):
groups[find(i)].append(i)
res = list(s)
for idx in groups.values():
for i, ch in zip(idx, sorted(s[i] for i in idx)):
res[i] = ch
return ''.join(res)JavaScript solution
function smallestStringWithSwaps(s, pairs) {
const parent = [...Array(s.length).keys()];
const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
for (const [a, b] of pairs) parent[find(a)] = find(b);
const groups = new Map();
for (let i = 0; i < s.length; i++) { const r = find(i); if (!groups.has(r)) groups.set(r, []); groups.get(r).push(i); }
const res = s.split('');
for (const idx of groups.values()) {
const chars = idx.map((i) => s[i]).sort();
idx.forEach((i, k) => { res[i] = chars[k]; });
}
return res.join('');
}