Smallest String With Swaps Problem
Description
LeetCode Problem 1202.
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.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Example 1:
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[1] and s[2], s = "bacd"
Example 2:
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
Explaination:
Swap s[0] and s[3], s = "bcad"
Swap s[0] and s[2], s = "acbd"
Swap s[1] and s[2], s = "abcd"
Example 3:
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
Explaination:
Swap s[0] and s[1], s = "bca"
Swap s[1] and s[2], s = "bac"
Swap s[0] and s[1], s = "abc"
Constraints:
1 <= s.length <= 10^50 <= pairs.length <= 10^50 <= pairs[i][0], pairs[i][1] < s.lengthsonly contains lower case English letters.
Solution
Approach: Union-Find, Then Sort Each Group
Swaps chain together. If you can swap positions a and b, and also b and c, then you can move characters between any of a, b and c. Using swaps as many times as you like, the characters inside one connected group of positions can be arranged in any order: adjacent swaps can produce every permutation. Characters can never move to a different group.
So the smallest string comes from handling each group on its own. Put the group's characters in sorted order into the group's positions, the smallest character at the smallest position. Making an earlier position smaller always beats anything at later positions, and this is the best each group can do.
- Join the two indices of every pair with union-find (with path halving, so
findis iterative and fast). A pair like[0, 0]is harmless. - Collect the indices of each group in increasing order, keyed by their root.
- For each group, sort its characters and write them back to its indices in order.
Complexity: O(n log n + p · α(n)) time, where p is the number of pairs and α is the very slowly growing inverse Ackermann function. O(n) extra space.
class Solution:
def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str:
n = len(s)
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
for a, b in pairs:
parent[find(a)] = find(b)
# Indices in each group, in increasing order.
groups = {}
for i in range(n):
groups.setdefault(find(i), []).append(i)
res = list(s)
for indices in groups.values():
# Inside a group the characters can be arranged in any order: put them in sorted order.
for i, ch in zip(indices, sorted(s[i] for i in indices)):
res[i] = ch
return "".join(res)