Smallest String With Swaps — LeetCode 1202 Python Solution

MediumDepth-First SearchBreadth-First SearchUnion FindArrayHash TableStringSorting
Problem
#1202
Pattern
Union-Find
Reading time
3 min

The problem

You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times.

Example

Input
s = "dcab", pairs = [[0,3],[1,2]]
Output
"bacd"

Python solution

Python
class Solution:
    def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
        def find(x: int) -> int:
            if p[x] != x:
                p[x] = find(p[x])
            return p[x]

        n = len(s)
        p = list(range(n))
        for a, b in pairs:
            p[find(a)] = find(b)
        d = defaultdict(list)
        for i, c in enumerate(s):
            d[find(i)].append(c)
        for i in d.keys():
            d[i].sort(reverse=True)
        return "".join(d[find(i)].pop() for i in range(n))

Complexity

MeasureComplexity
TimeO(n \times \log n + m \times \alpha(m))
SpaceO(n) auxiliary

Pattern: Union-Find

Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 1202. Smallest String With Swaps is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.

The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1202. Smallest String With Swaps?
LeetCode 1202. Smallest String With Swaps is rated Medium on LeetCode.
What is the time complexity of LeetCode 1202. Smallest String With Swaps?
The Python solution on this page runs in O(n \times \log n + m \times \alpha(m)).
What is the space complexity of LeetCode 1202. Smallest String With Swaps?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1202. Smallest String With Swaps cover?
LeetCode 1202. Smallest String With Swaps is tagged Depth-First Search, Breadth-First Search, Union Find, Array, Hash Table, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview