Python coding

Smallest string from allowed swaps

You get a string s and a list pairs of positions [i, j]. You may swap the letters at positions i and j of any listed pair, as many times as you like and in any order. Return the alphabetically smallest string you can reach.

s uses lowercase a–z and has at least one letter; every position is a valid index of s. A pair may repeat or have i == j. Aim for near-linear time plus sorting.

Besides the tests, one large input (2,000 letters, 2,499 pairs) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • smallest_after_swaps("tsyb", [[0,3],[1,2]]) → "bsyt"
  • smallest_after_swaps("golf", [[0,1],[1,2],[2,3]]) → "fglo"
  • smallest_after_swaps("hello", []) → "hello"
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Swaps chain: with pairs [0, 1] and [1, 2], the letter at 0 can reach 2. Positions joined by pairs, directly or through others, form groups, so union them.

Hint 2

Don't judge swaps one at a time: in "bac" with pairs [0, 2] and [1, 2], every single swap makes it worse, yet "abc" is reachable. Inside a group, swaps can produce any order of its letters.

Hint 3

Sort each group's letters and hand them to its positions from left to right: the smallest letters go to the earliest positions.

Solution and why it works
pythonO(n log n + m · α(n)), m = pairs · O(n)
def smallest_after_swaps(s: str, pairs: list[list[int]]) -> str:
    parent, size = list(range(len(s))), [1] * len(s)

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]        # path halving
            x = parent[x]
        return x

    for i, j in pairs:
        ri, rj = find(i), find(j)
        if ri != rj:
            if size[ri] < size[rj]:
                ri, rj = rj, ri
            parent[rj] = ri                      # smaller tree under the larger root
            size[ri] += size[rj]
    groups = {}
    for i in range(len(s)):
        groups.setdefault(find(i), []).append(i)     # positions of each group, in increasing order
    out = list(s)
    for positions in groups.values():
        for i, ch in zip(positions, sorted(s[i] for i in positions)):
            out[i] = ch                          # smallest letters to the earliest positions
    return "".join(out)

Swaps along a chain of pairs can carry any letter of a connected group to any of its positions, so the group's letters can end up in any order. Union-find builds the groups in near-linear time; then each group's letters, sorted, fill its positions from left to right, which puts the smallest letters as early as possible. The trap is greedy swapping: taking only swaps that improve the string at once gets stuck, as in "bac" with pairs [0, 2] and [1, 2].