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 s and a list pairs of position pairs, you may swap the two characters at any listed pair, as often as you like and in any order. Return the smallest string you can make, comparing strings the way a dictionary orders words: the first position where two strings differ decides, and the one with the earlier letter there is smaller.

Example 1
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explanation: swap positions 0 and 3 to get "bcad", then 1 and 2 to get "bacd".
Example 2
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Example 3
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explanation: positions 0 and 2 are never paired directly, but they can still trade letters through position 1.
Solution

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.

Example 1: the string dcab with pair [0,3] and pair [1,2]. Positions 0 and 3 form one group with letters d and b, positions 1 and 2 another with c and a. Each group puts its sorted letters back into its own positions, giving the result bacd.

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, where each position points to another position in its group, and following the pointers ends at one position, the group's root.

At the start every position is its own root, since parent[i] is i. For the pair [0,3] in Example 1, the root of 0 is pointed at the root of 3, so 0 and 3 now share root 3. Asking "which group is position 0 in?" means following the pointers from 0 to its root, and that is the find step. Two positions are in the same group exactly when find gives them the same root.

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 points each position it passes at its grandparent, which is called path halving.

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> per group does both at once. Filled with d and b for group {0, 3}, the queue hands out b first and d second: it always gives up its smallest item, which makes it a min-heap. Characters are compared in alphabet order, so poll() returns the earliest letter still left. Walking the string from position 0 upward and taking one letter from that position's group each time places the group's letters in sorted order across its positions.

Java Solution

The method smallestStringWithSwaps works in these steps:

  1. First, create the array parent, one entry per position of the string, and set parent[i] = i, so every position starts as its own group.
  2. Loop over pairs. For each pair, find the roots of its two positions and point the first root at the second, which merges the two groups.
  3. Create the map letters, 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.
  4. Create a StringBuilder named sb. A second loop over the positions, left to right, takes the smallest letter left in the position's group with poll() and appends it to sb.
  5. When that loop is done, sb holds the new string, and the method returns it.

The main method runs the three examples, then "dcab" with no pairs at all, and then "zbza" with a pair listed twice in both orders plus a position paired with itself.

Java
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:

Output
bacd
abcd
abc
dcab
abzz

The output starts with bacd, abcd and abc, the answers to the three examples. The third one, abc, is the chain at work: the a moved from position 2 to position 0 without any pair [0,2]. Going through the pairs once, swapping only when it helps, stops at bac for the same input, because the pair [0,1] is not used again once the a reaches position 1.

With no pairs, dcab comes back unchanged, because every position stays its own group with a single letter. The last line, abzz, comes from "zbza". The pairs [0,3] and [3,0] merge the same two positions, and the second one changes nothing, since both already share a root. The pair [2,2] does nothing either. Only positions 0 and 3 trade, so the a moves to the front and the z goes to position 3.

Complexity

The work is one merge per pair, then two passes over the positions, each with a find and a heap operation.

  • 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 parent array has one entry per position, the heaps together hold each of the n characters once, and sb builds a string of n characters.

Union-find on a graph of numbered points is explained further in Number of Connected Components.