Smallest String With Swaps solution explained
The key to Smallest String With Swaps is that swap pairs connect positions into groups, and inside a connected group the letters can be rearranged into any order. So union the paired indexes with a disjoint set, then for each group sort its letters and write them back into its positions from left to right. That runs in O(n log n + p · α(n)) time for a string of length n and p pairs.
By Evin JohnPublished 7 min read
The problem in our own words
You get a lowercase string and a list of index pairs. For any listed pair (i, j), you may swap the characters at positions i and j, and you may do this as many times as you want, in any order, using any pairs. Return the lexicographically smallest string you can produce, meaning the one that would come first in a dictionary.
| String | Pairs | Smallest result | Groups of positions |
|---|---|---|---|
| tavern | (0, 5), (5, 2), (1, 4) | naterv | {0, 2, 5} holds t, v, n; {1, 4} holds a, r |
| sorted | (0, 3), (3, 5), (1, 2) | dorset | {0, 3, 5} holds s, t, d; {1, 2} holds o, r |
| zyx | (0, 1), (1, 2) | xyz | One group covers the whole string |
| mango | (1, 3), (3, 4) | mango | {1, 3, 4} holds a, g, o, already in order |
| bead | none | bead | No swaps allowed |
In the tavern row, positions 0 and 2 are never paired directly, but both are paired with 5, so the three of them form one group. That chain effect is the whole problem. Ask the interviewer whether pairs can repeat or contain the same index twice; both are harmless for the approach below, but it shows you are reading the input.
What the interviewer is testing
There are two ideas to find. The first is that the swap relation is transitive through chains, so you are really looking at connected components of a graph whose nodes are positions. The second, and the one candidates often skip, is why any order is reachable inside a component. If you cannot explain that, the sort step looks like a guess.
Why every arrangement is reachable
Take a connected group and pick a spanning tree of its pairs. You can carry any letter to any position in the group by swapping it along the tree path, one edge at a time. That is how bubble sort works on a line, and a tree path is just a line. Now pick a leaf of the tree, carry the letter it should end with into it, and set that leaf aside. What remains is still a connected tree, so repeat until every position holds its target letter. Formally, transpositions along the edges of a connected graph generate every permutation of its nodes.
Slow approach: explore every reachable string
Treat each string as a state and each allowed swap as a move. A breadth-first search from the start string visits every reachable state, and the answer is the minimum of them. This is a useful check on tiny inputs, which is how the main solution on this page was tested, but a group of size g has up to g factorial arrangements.
from collections import deque
def smallest_after_swaps_slow(s, pairs):
seen, queue = {s}, deque([s])
while queue:
cur = queue.popleft()
for a, b in pairs:
nxt = list(cur)
nxt[a], nxt[b] = nxt[b], nxt[a]
nxt = "".join(nxt)
if nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return min(seen)Main approach: components, then sort each one
Build a disjoint set over the n positions and union every pair. Then group positions by their root. Because you scan positions from 0 upward, each group's list of positions comes out already sorted. Take the letters at those positions, sort them, and write the smallest letter into the smallest position, the next into the next, and so on. Different groups never interact, so each can be handled on its own.
This version uses a recursive find with path compression and union by size. Union by size keeps trees shallow, so the recursion depth stays around log n even before compression flattens it.
from collections import defaultdict
def smallest_after_swaps(s, pairs):
n = len(s)
parent = list(range(n))
size = [1] * n
def find(i):
if parent[i] != i:
parent[i] = find(parent[i])
return parent[i]
for a, b in pairs:
ra, rb = find(a), find(b)
if ra == rb:
continue
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
members = defaultdict(list)
for i in range(n):
members[find(i)].append(i)
chars = list(s)
for spots in members.values():
for i, ch in zip(spots, sorted(s[j] for j in spots)):
chars[i] = ch
return "".join(chars)function smallestAfterSwaps(s, pairs) {
const n = s.length;
const parent = Array.from({ length: n }, (_, i) => i);
const size = new Array(n).fill(1);
const find = (i) => (parent[i] === i ? i : (parent[i] = find(parent[i])));
for (const [a, b] of pairs) {
let ra = find(a);
let rb = find(b);
if (ra === rb) continue;
if (size[ra] < size[rb]) [ra, rb] = [rb, ra];
parent[rb] = ra;
size[ra] += size[rb];
}
const members = new Map();
for (let i = 0; i < n; i++) {
const r = find(i);
if (!members.has(r)) members.set(r, []);
members.get(r).push(i);
}
const out = s.split("");
for (const spots of members.values()) {
const letters = spots.map((i) => s[i]).sort();
spots.forEach((pos, k) => {
out[pos] = letters[k];
});
}
return out.join("");
}A small note on the JavaScript sort: with no comparator it orders by UTF-16 code units, which is exactly alphabetical for lowercase letters. The same call would be wrong on numbers, where 10 sorts before 9, so do not carry the habit over blindly.
Cost of each approach
| Approach | Time | Additional space | Verdict |
|---|---|---|---|
| Search all reachable strings | Up to O(n! · p · n) | Up to O(n! · n) | Tiny inputs only |
| Union-find plus comparison sort | O(p · α(n) + n log n) | O(n) | Standard answer |
| Union-find plus counting sort per group | O(p · α(n) + 26 · groups + n) | O(n) | Linear when the alphabet is fixed |
A graph search works just as well as union-find for finding the components: build an adjacency list and run DFS or BFS from each unvisited position. It has the same asymptotic cost. Union-find is shorter to write and does not need the adjacency list, which is why most people reach for it here.
Test inputs to try
- No pairs at all: return the string unchanged.
- A pair that repeats, or a pair (i, i): unions are idempotent, so nothing breaks.
- Pairs that form a cycle: still one component, and union-find simply skips the redundant pair.
- A string of identical letters: the answer is the same string.
- A component that is already sorted, like mango above: the output should equal the input.
Frequent errors
- Applying each pair once, greedily, only when it helps. A swap that looks useless now can be needed later to move a letter along a chain.
- Sorting letters but writing them into positions in root order instead of ascending index order.
- Using a recursive find with no union by size on a long chain of pairs, which can blow the recursion limit in Python.
- Building a new string inside the loop with repeated concatenation, which can turn linear work quadratic.
- Forgetting that unpaired positions are their own groups of one and must still be copied.
An answer you could give
Fictional example
- Candidate
- Swaps chain together, so positions connected by any path of pairs form a group, and within a group I can reach any arrangement by moving letters along that path.
- Candidate
- I union all the pairs, collect positions by root in ascending order, sort each group's letters, and place them smallest first.
- Candidate
- Union-find is nearly linear in the number of pairs, and the sorting adds n log n overall, or linear with counting sort on 26 letters.
Where to go next
Lexicographically Smallest Equivalent String is a close cousin: union-find again, but over the 26 letters instead of positions, and it keeps the smallest letter as each set's root. Number of Islands II applies the structure to a growing grid. The data structure interview questions page has more on disjoint sets.
Rehearse it with Natively
In practice sessions, Natively can read the problem from a screenshot and suggest code, which you can compare against your own after a timed attempt. It also transcribes the mock interview on your computer, so you can go back and see whether your explanation of why any order is reachable was clear. Learn more about an AI interview assistant on Mac and Windows.
Questions people ask
How do you solve Smallest String With Swaps?
Union every swap pair in a disjoint set, group positions by root, sort the letters of each group, and write them back into that group's positions in ascending index order.
Why can the letters in a group be put in any order?
Positions in a group are connected by a chain of allowed swaps, so any letter can travel to any position along a path, like bubble sort. Swaps along the edges of a connected graph can produce every permutation.
What is the time complexity?
O(p · α(n)) for the unions plus O(n log n) for the sorting, where n is the string length and p the number of pairs. Counting sort over 26 letters makes the sorting step linear.
Can I use DFS instead of union-find?
Yes. Build an adjacency list from the pairs and run DFS or BFS to find components. The complexity is the same; union-find is just shorter to write here.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
