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
Smallest String With SwapsTransform string to lexicographically smallest by swapping allowed pairsInput:s = "dcba", pairs = [[0,3],[1,2]]dcba01230↔31↔2Process:Group 1: {0,3} → [d,a] → sort → [a,d]Group 2: {1,2} → [c,b] → sort → [b,c]Output:abcd"abcd"
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
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
89.4K Views
Medium Frequency
~25 min Avg. Time
2.8K 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