1. Description
Each pair [a, b] in pairs lets you exchange the characters at zero-based positions a and b in the string s. You can reuse any pair as often as needed.
Return the lexicographically smallest string reachable from s.
2. Example
Example 1
Input: s = “dcab”, pairs = [[0,3],[1,2]]
Output: “bacd”
Explanation: Swapping positions 0 and 3 gives “bcad”. Swapping positions 1 and 2 then gives “bacd”.
Example 2
Input: s = “dcab”, pairs = [[0,3],[1,2],[0,2]]
Output: “abcd”
Explanation: The extra pair [0,2] connects all four positions, so the letters can be arranged in sorted order.
Example 3
Input: s = “cba”, pairs = [[0,1],[1,2]]
Output: “abc”
Explanation: The allowed swaps give the sequence “cba” → “bca” → “bac” → “abc”.
3. Constraints
- 1 <= s.length <= 10$^5$
- 0 <= pairs.length <= 10$^5$
- Both indices in each pair are between 0 and s.length - 1, inclusive.
- Each character in s is a lowercase English letter.
4. Solutions
Union Find && Sorting
n = s.length, m = pairs.length, α = inverse Ackermann function
Time complexity: O((m + n) α(n) + n log n) on average
Space complexity: O(n)
| |