Trains the technique from
LeetCode 1202Smallest String With SwapsThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A label is printed as the lowercase string s, one letter per slot, numbered from 0.
The printer can exchange the letters in certain slots. Each entry pairs[i] = [a, b] says the letters in slots a and b may trade places. An exchange listed in pairs may be carried out as often as you like, in any order, and the same entry may appear more than once. An entry may also name the same slot twice, which changes nothing.
Return the alphabetically earliest label reachable through any number of these exchanges.
Example 1
Slots 0 and 5 hold m and a and may trade, so a moves to the front. Slots 2 and 4 hold b and t and may trade, but b is already the earlier letter. Slots 1 and 3 appear in no entry.
Example 2
Slots 0, 3 and 5 are linked into one group holding z, w and u, so those three letters end up as u, w, z across slots 0, 3 and 5. Slots 1 and 4 form a second group holding y and v, which come out as v then y. Slot 2 keeps x.
Example 3
There are three separate groups of two slots each, and no letter can leave its own group, so each pair simply comes out in alphabetical order.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def smallest_string_with_swaps(s: str, pairs: list[list[int]]) -> str:public String smallestStringWithSwaps(String s, List<List<Integer>> pairs)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.