1202. Smallest String With Swaps

LeetCode 力扣

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)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
    string smallestStringWithSwaps(string &str, vector<vector<int>> &pairs) {
        const int n = str.size();
        vector<int> parent(n);
        vector<int> sizes(n, 1);
        iota(parent.begin(), parent.end(), 0);

        for (auto &p : pairs) {
            int root_x = find(parent, p[0]);
            int root_y = find(parent, p[1]);

            if (root_x == root_y) {
                continue;
            }

            if (sizes[root_x] > sizes[root_y]) {
                swap(root_x, root_y);
            }

            parent[root_x] = root_y;
            sizes[root_y] += sizes[root_x];
        }

        unordered_map<int, string> groups;
        for (int i = 0; i < n; ++i) {
            groups[find(parent, i)].push_back(str[i]);
        }

        for (auto &[root, letters] : groups) {
            sort(letters.rbegin(), letters.rend());
        }

        for (int i = 0; i < n; ++i) {
            string &letters = groups[find(parent, i)];
            str[i] = letters.back();
            letters.pop_back();
        }

        return str;
    }

private:
    int find(vector<int> &parent, int x) {
        if (parent[x] != x) {
            parent[x] = find(parent, parent[x]);
        }

        return parent[x];
    }
};
comments powered by Disqus