Intuition
If you can swap index a with b, and b with c, then by repeating swaps you can arrange the characters at a, b and c into any order you like. So each pair is really a 'these indices can be freely rearranged' link. Group the indices into connected components, and within one component sort its characters and drop them back into the component's positions in index order — smallest character into the smallest index.
Explanation
Key idea
A single pair [a, b] lets you swap two characters. But you may use each pair any number of times, and pairs chain together: if [a, b] and [b, c] are both allowed, then a, b, c are all mutually reachable. With repeated swaps you can realise any permutation of the characters sitting at the indices of one connected group.
That collapses the problem: for each connected group of indices, the set of characters there is fixed, but you may place them in any order. To get the lexicographically smallest overall string, sort that group's characters ascending and write them into the group's indices from smallest index to largest.
Steps
- Union-Find over indices. Start with
parent[i] = i. For every pair[a, b], unionaandb. - Group indices by root. Walk every index
iand append it togroups[find(i)]. - Sort within each group. For each group, collect the characters at those indices, sort them, sort the indices, and assign the k-th smallest character to the k-th smallest index.
- Join the characters back into a string.
Walk-through
s = "dcab", pairs = [[0, 3], [1, 2]].
Union step. union(0, 3) links indices 0 and 3; union(1, 2) links indices 1 and 2. Two components form: {0, 3} and {1, 2}.
Component {0, 3}. Characters are s[0]='d' and s[3]='b'. Sorted: b, d. Indices sorted: 0, 3. Place b at 0 and d at 3 → positions 0 and 3 become b and d.
Component {1, 2}. Characters are s[1]='c' and s[2]='a'. Sorted: a, c. Indices sorted: 1, 2. Place a at 1 and c at 2 → positions 1 and 2 become a and c.
Reading the string back: index 0 = b, 1 = a, 2 = c, 3 = d → "bacd". ✓
Why sorting each group is optimal
Lexicographic order compares the earliest differing position first, so you always want the smallest possible character as far left as possible. Within a group you are free to choose the arrangement, and placing the sorted characters into the sorted indices puts the smallest character at the earliest index of the group — which is exactly the greedy choice lexicographic order rewards. Indices in different groups never interact, so each group can be optimised independently.
Edge cases
- No pairs: every index is its own group, nothing can move, the answer is
sunchanged. - All indices in one group: the whole string can be freely rearranged, so the answer is simply its characters sorted ascending.
Complexity
- Time:
O(n log n + m · α(n))wheren = len(s),m = len(pairs), andαis the inverse Ackermann function (effectively constant). Then log ncomes from sorting characters within groups. - Space:
O(n)for the Union-Find arrays and the per-group buckets.
Implementation
import java.util.*;
class Solution {
private int[] parent;
private int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
private void union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra != rb) parent[ra] = rb;
}
public String smallestStringWithSwaps(String s, int[][] pairs) {
int n = s.length();
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
for (int[] p : pairs) {
union(p[0], p[1]);
}
Map<Integer, List<Integer>> groups = new HashMap<>();
for (int i = 0; i < n; i++) {
groups.computeIfAbsent(find(i), k -> new ArrayList<>()).add(i);
}
char[] res = s.toCharArray();
for (List<Integer> indices : groups.values()) {
List<Character> chars = new ArrayList<>();
for (int i : indices) chars.add(res[i]);
Collections.sort(chars);
Collections.sort(indices);
for (int k = 0; k < indices.size(); k++) {
res[indices.get(k)] = chars.get(k);
}
}
return new String(res);
}
}