You are given a string s of lowercase English letters and an array pairs, where pairs[i] = [a, b] names two 0-indexed positions in s.
You can swap the characters at the two positions of any pair in pairs, any number of times and in any order.
Return the lexicographically smallest string that s can be changed to after using the swaps.
Function Signature
def smallest_string_with_swaps(s: str, pairs: list[list[int]]) -> str:
Rules
-
Each element of
pairs
is a two-element list
[a, b]
of indices into
s
.
-
Every pair can be used as many times as you like, including zero times, so
s
itself is always reachable.
-
A pair may appear more than once, and a pair with
a == b
is allowed (swapping a position with itself changes nothing).
Constraints
-
1 <= len(s) <= 10^5
-
0 <= len(pairs) <= 10^5
-
0 <= pairs[i][0], pairs[i][1] < len(s)
-
s
contains only lowercase English letters.
Examples
Input: s = "dcab", pairs = [[0,3],[1,2]]
Output: "bacd"
Positions 0 and 3 can only trade with each other, and so can positions 1 and 2. Swapping 0 and 3 gives "bcad", and swapping 1 and 2 then gives "bacd", which puts the smaller letter of each group first.
Input: s = "dcab", pairs = [[0,3],[1,2],[0,2]]
Output: "abcd"
The pair [0,2] joins the two groups, so all four positions are connected and the letters can be fully sorted.
Input: s = "cba", pairs = [[0,1],[1,2]]
Output: "abc"
No pair links positions 0 and 2 directly, but both link to position 1. Swapping 0 and 1 ("bca"), then 1 and 2 ("bac"), then 0 and 1 again gives "abc".