Smallest String With Swaps
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Union Find.
Smallest String With Swaps
Given a string
s and pairs of indices that can be swapped, return the lexicographically smallest string possible.Examples
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Approach 1
Level III: Union-Find + Sorting (Optimal)
Intuition
Indices that can swap form connected components. All characters within a component can be moved to any index in that component. Sort characters for each component and place them in sorted index order.
⏱ O(N \log N)💾 O(N)
Detailed Dry Run
Indices {0, 3} are connected. Characters are s[0]='d', s[3]='b'. Sorted: 'b', 'd'. Place 'b' at index 0 and 'd' at index 3.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.