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 Swaps - DFS Connected Components INPUT String s = "dcba" d idx 0 c idx 1 b idx 2 a idx 3 Pairs = [[0,3], [1,2]] Graph Representation: 0 1 2 3 [0,3] [1,2] Component 1 Component 2 ALGORITHM STEPS 1 Build Graph Add edges for each pair 2 Find Components (DFS) Group connected indices Component 1 indices: {0, 3} chars: {d, a} Component 2 indices: {1, 2} chars: {c, b} 3 Sort Each Component Sort indices and chars Sorted Comp 1 indices: [0, 3] chars: [a, d] Sorted Comp 2 indices: [1, 2] chars: [b, c] 4 Assign Characters Place sorted chars at indices 0-->a, 1-->b, 2-->c, 3-->d result = "abcd" FINAL RESULT Original: "dcba" d c b a Result: "abcd" a b c d Output: "abcd" [OK] Lexicographically Smallest String Key Insight: If indices are connected (directly or indirectly via swaps), characters at those positions can be rearranged in any order. Using DFS to find connected components allows us to sort characters within each component independently, achieving the lexicographically smallest result. Time: O(n log n) TutorialsPoint - Smallest String With Swaps | DFS Connected Components Approach
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