mediumUnion FindStringUnion Find

Smallest String With Swaps

mediumTime: O(n log n)Space: O(n)

Recognize the pattern

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

Brute force idea

A straightforward first read of Smallest String With Swaps is this: 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.

Better approach

The deeper shift in Smallest String With Swaps is this: 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.

Key invariant

At the center of Smallest String With Swaps is one steady idea: 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.

Watch out for

A common way to get lost in Smallest String With Swaps is this: 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