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

example_1.py — Basic Case
$ Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
💡 Note: Indices 0 and 3 can swap (d↔b), indices 1 and 2 can swap (c↔a). We can rearrange to get 'bacd' which is lexicographically smallest.
example_2.py — Transitive Swaps
$ Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
💡 Note: Now all indices are connected transitively: 0↔3, 1↔2, 0↔2 means 0,1,2,3 form one group. We can arrange all characters optimally to get 'abcd'.
example_3.py — No Swaps Possible
$ Input: s = "cba", pairs = []
Output: "cba"
💡 Note: No pairs means no swaps possible, so the string remains unchanged.

Visualization

Tap to expand
Connected Components StrategyOriginal String: "dcab"dpos 0cpos 1apos 2bpos 3Swap Pairs: [0,3], [1,2]can swapdbcan swapcaResult: "bacd"bacdUnion-Find MagicGroup 1: {d, b} → sort → {b, d}Group 2: {c, a} → sort → {a, c}Place back at original positions:pos 0: b, pos 1: apos 2: c, pos 3: dFinal: "bacd"
Understanding the Visualization
1
Map Connections
Use Union-Find to build connected components from swap pairs
2
Group Characters
Collect all characters that belong to each connected component
3
Sort and Place
Sort characters within each group and place them back optimally
Key Takeaway
🎯 Key Insight: Use Union-Find to group indices that can swap transitively, then sort characters within each group for optimal lexicographic result.

Time & Space Complexity

Time Complexity
⏱️
O(n α(n) + m α(n))

Union-Find operations with path compression, where α is the inverse Ackermann function (practically constant)

n
2n
Linear Growth
Space Complexity
O(n)

Space for Union-Find structure and temporary character storage

n
2n
Linearithmic Space

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
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
52.3K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen