Smallest String With Swaps (LeetCode 1202): Solution and Explanation

Medium
Array
Hash Table
String
Depth First Search
Breadth First Search
Union Find
Sorting

Each pair [a, b] lets you swap the letters at indices a and b as often as you like. Return the lexicographically smallest string you can reach. For s = "dcab" with pairs [[0,3],[1,2]] the answer is "bacd".

Intuition

Treat indices as nodes and pairs as edges. A swap only moves letters along an edge, but repeated swaps along a path can carry a letter anywhere in its connected component.

In fact adjacent swaps generate every permutation, so inside one component the letters can be arranged in any order at all. Letters can never cross between components.

To make the string as small as possible, each component should hold its letters in sorted order, with the smallest letter at the component's smallest index.

Approach: Union-find, then sort each group

  1. Create a parent array where every index is its own root.
  2. For each pair, find both roots and join them if they differ.
  3. Group the indices by root. Walking i from 0 to n - 1 keeps each group's indices in increasing order.
  4. For each group, sort its letters and write them back to its indices in order.
  5. Join the result into a string.

Step-by-step example

s = "dcab", pairs = [[0,3],[1,2]]
  1. Pair [0,3] joins indices 0 and 3. Pair [1,2] joins indices 1 and 2.
  2. Groups: {0, 3} with letters d, b and {1, 2} with letters c, a.
  3. Sort {0, 3}: b goes to index 0 and d to index 3.
  4. Sort {1, 2}: a goes to index 1 and c to index 2. The answer is "bacd".

Code: Python, Java, C++

1class Solution:
2    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
3        n = len(s)
4        parent = list(range(n))
5
6        def find(x):
7            while parent[x] != x:
8                parent[x] = parent[parent[x]]
9                x = parent[x]
10            return x
11
12        for a, b in pairs:
13            ra, rb = find(a), find(b)
14            if ra != rb:
15                parent[ra] = rb
16        groups = {}
17        for i in range(n):
18            groups.setdefault(find(i), []).append(i)
19        res = list(s)
20        for idx in groups.values():
21            chars = sorted(s[i] for i in idx)
22            for i, c in zip(idx, chars):
23                res[i] = c
24        return ''.join(res)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n + m α(n))

Each of the m pairs costs a near-constant union-find operation, and sorting all groups together costs at most O(n log n). Counting sort over 26 letters makes that part O(n).

Space

O(n)

The parent array, the groups and the result each hold n entries.

Other approaches

DFS over an adjacency list (time O(n log n + m), space O(n + m))

Build the graph from the pairs and run DFS from each unvisited index to collect a component, then sort its indices and letters. Same idea, with recursion depth to watch on long chains.

Union-find with counting sort (time O(n + m α(n)), space O(n))

Instead of sorting each group's letters, count the 26 letters per group and hand them out in order. This removes the log factor.

Common mistakes

  • Only swapping the pairs directly once each, greedily. Swaps chain through shared indices, so you must treat whole components.
  • Sorting the letters but forgetting to sort the indices they go back into. The smallest letter must land at the smallest index of the group.
  • Recursive find on a chain of 10^5 indices can overflow the stack in Python. Use path compression in a loop or union by rank.

Frequently asked questions

Why can any order be reached inside a component?

Swapping along the edges of a spanning tree lets you move one letter to any position without disturbing the rest permanently, like bubble sort along a path. Repeating this builds any permutation.

Do repeated or self pairs matter?

No. A pair whose ends already share a root changes nothing, and a pair like [2, 2] is a no-op swap.

Does the order of the pairs matter?

No. Only which indices end up connected matters, and union-find gives the same components in any order.