Smallest String With Swaps
Master this topic with zero to advance depth.
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.