Smallest String With Swaps
Problem Statement
You get a string s and a list of index pairs. Each pair [a, b] lets you swap the letters at positions a and b. You may use these swaps as many times as you like, in any order.
Return the smallest string (in dictionary order) that you can reach.
s: a string of lowercase letters. pairs: a list of [a, b] index pairs.
The smallest string that any sequence of the allowed swaps can produce.
Swap indices 0 and 3: "bcad". Swap indices 1 and 2: "bacd". Nothing better is reachable with these two pairs.
The pairs (0, 3) and (0, 2) join indices 0, 2 and 3. The pair (1, 2) then joins index 1 to them, so all four indices form one group and their letters can be sorted freely.
Index 0 can trade with 1, and 1 can trade with 2, so all three letters can be sorted.
- • 1 <= s.length <= 10^5
- • 0 <= pairs.length <= 10^5
- • 0 <= pairs[i][0], pairs[i][1] < s.length
- • s only contains lowercase English letters
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
BFS over all strings reachable by swaps, keeping the smallest
DSU over indices; write each group's sorted letters back into its indices in order
Start from s. From each string you reach, apply every allowed swap to get new strings. Keep a set of the strings already seen, so each one is expanded once. The answer is the smallest string the search reaches. Every swap can be undone by the same swap, so the search covers everything reachable.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Union-Find (DSU) translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.