Problem Statement

Smallest String With Swaps

You are given a string s and a list of pairs of positions in that string. Each pair, like [a, b], means you are allowed to swap the letter at position a with the letter at position b. You can do each allowed swap as many times as you want. Your job is to return the smallest possible string you can make, where "smallest" means alphabetical order (the word that would come first in a dictionary). Here is the trick that makes this easy. If you can swap position a with position b, and you can swap position b with position c, then by chaining swaps you can move a letter from a all the way to c. So a, b, and c form one connected group, and inside that group you can put the letters in any order you like. Each group of connected positions can be sorted on its own, separately from the others.

mediumUnion FindStringUnion FindTime: O(n log n) · Space: O(n)

Signals to notice

can swap characters at given index pairsswaps are transitivesort within connected groups

Brute force first

Apply swaps greedily until no improvement — convergence is slow and hard to prove optimal. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Union-Find: the swap pairs define connectivity. Within each connected component, you can arrange characters in any order (via a chain of swaps). Sort characters within each group to get the lexicographically smallest result. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on s="dcab", pairs=[[0,3],[1,2]]

init: parent=[0,1,2,3], result=['d','c','a','b']
union(0,3): parent[3]=0 -> {0,3} linked, rank[0]=1
union(1,2): parent[2]=1 -> {1,2} linked, rank[1]=1
group by find(i): {root0:[0,3], root1:[1,2]}
group [0,3]: chars 'd','b' -> sorted 'b','d'; result[0]='b', result[3]='d'
group [1,2]: chars 'c','a' -> sorted 'a','c'; result[1]='a', result[2]='c'
result=['b','a','c','d'] -> return "bacd"

What must stay true

If positions i and j are connected (directly or through a chain of swaps), you can achieve any permutation of characters at those positions. So sort each group's characters to minimize the result. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

parent = [0..n-1]
for (a, b) in pairs: union(a, b)         // build connected components
groups = group indices by find(i)
for indices in groups:
    place sorted(chars at indices) into sorted(indices)
return joined result

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Thinking you can only swap directly connected positions — transitivity means if (0,1) and (1,2) are pairs, positions 0 and 2 can also be swapped (via position 1). Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Union Find Pattern