Imagine you have a string of characters and a special set of swap rules that allow you to exchange characters at specific positions. Your goal is to create the lexicographically smallest string possible using these swaps.
Given a string s and an array of pairs pairs where pairs[i] = [a, b] indicates you can swap characters at indices a and b, you can perform these swaps any number of times. The key insight is that if you can swap AโB and BโC, then effectively you can rearrange A, B, and C in any order!
Goal: Return the lexicographically smallest string after optimally using all available swaps.
Example: With string "dcab" and pairs [[0,3],[1,2]], you can swap positions (0,3) and (1,2) to get "bacd" - the smallest possible arrangement.
Input & Output
Visualization
Time & Space Complexity
Union-Find operations with path compression, where ฮฑ is the inverse Ackermann function (practically constant)
Space for Union-Find structure and temporary character storage
Constraints
- 1 โค s.length โค 105
- 0 โค pairs.length โค 105
- 0 โค pairs[i][0], pairs[i][1] < s.length
- pairs[i][0] โ pairs[i][1]
- s contains only lowercase English letters