Smallest String With Swaps
Find the smallest string you can reach when only some pairs of positions are allowed to trade letters.
Given a string spairs
Example 1
Output: "bacd"
Explanation: swap positions 0 and 3 to get "bcad", then 1 and 2 to get "bacd".
Example 2
Output: "abcd"
Example 3
Output: "abc"
Explanation: positions 0 and 2 are never paired directly, but they can still trade letters through position 1.
The Idea
Imagine four letter tiles in a row on a shelf, reading d, c, a, b. Some spots are joined by a cord, and only tiles on two joined spots may change places. In Example 1, spot 0 is joined to spot 3, and spot 1 to spot 2.
Look at the picture below. The blue arc is the pair [0,3] and the teal arc is the pair [1,2]. The d at position 0 and the b at position 3, drawn in blue, can trade places, and so can the teal c and a in the middle. No arc reaches from a blue tile to a teal one, so a blue letter can never land on a teal spot.
So the positions fall into groups: the box labelled group {0, 3} holds the letters d and b, and the box labelled group {1, 2} holds c and a. Inside a group the letters can be swapped as much as we like. To make the string small, the earliest position should get the smallest letter, so each group sorts its letters and puts them back left to right. Group {0, 3} puts b at 0 and d at 3, group {1, 2} puts a at 1 and c at 2, and the result row reads b, a, c, d.
Example 3 raises a question. "cba" has the pairs [0,1] and [1,2], but no pair [0,2]. Can the c at position 0 still reach position 2? Yes: swap 0 and 1 to get "bca", then 1 and 2 to get "bac", then 0 and 1 again to get "abc". A letter can travel along a chain of pairs, one hop at a time.
That is the key insight. Two positions are in the same group when a chain of pairs links them, not only when they are paired directly. Within such a group, repeated swaps can put the letters in any order. Example 2 shows it: the extra pair [0,2] links group {0, 3} to group {1, 2}, all four positions become one group, and sorting the letters a, b, c, d gives "abcd".
Solution Approach
Turning that idea into code means settling three things: why swapping pair by pair is not enough, how to find the groups, and how to hand each group's letters out in sorted order.
Swapping pair by pair
Why not go through the pairs and swap whenever the swap puts a smaller letter first? For "cba", the pair [0,1] gives "bca" and the pair [1,2] gives "bac". The a still sits behind the b, because reaching "abc" needs the pair [0,1] a second time. Listing every string that some sequence of swaps can reach would work, but ten linked positions with ten different letters can already be arranged in 3,628,800 ways. Finding the groups avoids listing any of them.
Finding the groups
How do we learn which positions are linked by a chain? Treat each position as a member of a group and each pair as an instruction to merge the groups of its two positions. A structure that does exactly this is called union-find. It keeps an array parent
At the start every position is its own root, since parent[i]ifindfind
Chains need no extra work. In Example 3, the pair [0,1] puts 0 under 1, and the pair [1,2] puts 1 under 2, so the pointers lead from 0 to 1 to 2, and all three positions share root 2. To keep such walks short, find
Handing out the letters in sorted order
Each group now needs its letters sorted, and its positions filled from left to right. A PriorityQueue<Character>poll()
Java Solution
The method smallestStringWithSwaps
- First, create the array
, one entry per position of the string, and setparent , so every position starts as its own group.parent[i] = i - Loop over
. For each pair,pairs the roots of its two positions and point the first root at the second, which merges the two groups.find - Create the map
, from a group's root to that group's min-heap. A loop over the positions adds each character to the heap of its root, creating the heap the first time a root shows up.letters - Create a
namedStringBuilder . A second loop over the positions, left to right, takes the smallest letter left in the position's group withsb and appends it topoll() .sb - When that loop is done,
holds the new string, and the method returns it.sb
The main
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class SmallestStringWithSwaps {
public static String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
int n = s.length();
int[] parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every position starts as its own group
}
for (List<Integer> p : pairs) {
parent[find(parent, p.get(0))] = find(parent, p.get(1)); // join two groups
}
// One min-heap per group, keyed by the group's root, holding the group's letters.
Map<Integer, PriorityQueue<Character>> letters = new HashMap<>();
for (int i = 0; i < n; i++) {
letters.computeIfAbsent(find(parent, i), k -> new PriorityQueue<>()).add(s.charAt(i));
}
// Left to right, each position takes the smallest letter left in its group.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(letters.get(find(parent, i)).poll());
}
return sb.toString();
}
private static int find(int[] parent, int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]]; // skip a level on the way up
x = parent[x];
}
return x;
}
public static void main(String[] args) {
System.out.println(smallestStringWithSwaps("dcab", List.of(List.of(0, 3), List.of(1, 2))));
System.out.println(smallestStringWithSwaps("dcab",
List.of(List.of(0, 3), List.of(1, 2), List.of(0, 2))));
System.out.println(smallestStringWithSwaps("cba", List.of(List.of(0, 1), List.of(1, 2))));
System.out.println(smallestStringWithSwaps("dcab", List.of()));
System.out.println(smallestStringWithSwaps("zbza",
List.of(List.of(0, 3), List.of(3, 0), List.of(2, 2))));
}
}
Running it prints:
bacd
abcd
abc
dcab
abzz
The output starts with bacdabcdabcabcbac
With no pairs, dcababzz
Complexity
The work is one merge per pair, then two passes over the positions, each with a find
- Time: O((n + P) log n) for n characters and P pairs, because each merge and each of the 2n lookups costs O(log n) on average with path halving, as does each heap insert and poll.
- Space: O(n), because the
array has one entry per position, the heaps together hold each of the n characters once, andparent builds a string of n characters.sb
Union-find on a graph of numbered points is explained further in