Smallest String With Swaps - Problem
You are given a string s and an array of pairs of indices pairs where pairs[i] = [a, b] indicates 2 indices (0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Input & Output
Example 1 — Basic Swapping
$
Input:
s = "dcba", pairs = [[0,3],[1,2]]
›
Output:
"abcd"
💡 Note:
Position 0 can swap with 3 (d↔a), position 1 can swap with 2 (c↔b). Optimal arrangement: a,b,c,d gives "abcd"
Example 2 — Transitive Connections
$
Input:
s = "dcba", pairs = [[0,3],[1,2],[0,2]]
›
Output:
"abcd"
💡 Note:
All positions are connected transitively: 0↔3, 1↔2, 0↔2 means all can swap. Sort all chars: [a,b,c,d] gives "abcd"
Example 3 — No Swaps Possible
$
Input:
s = "cba", pairs = []
›
Output:
"cba"
💡 Note:
No pairs given, so no swaps are allowed. String remains unchanged: "cba"
Constraints
- 1 ≤ s.length ≤ 105
- 0 ≤ pairs.length ≤ 105
- 0 ≤ pairs[i][0], pairs[i][1] < s.length
- s contains only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with allowed swap pairs
2
Group Connections
Find transitively connected positions
3
Sort Within Groups
Arrange characters optimally in each group
Key Takeaway
🎯 Key Insight: Group transitively connected positions and sort characters within each group for optimal lexicographic arrangement
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code