mediumUnion FindStringUnion Find

Smallest String With Swaps

mediumTime: 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.

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.

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