1202 — Smallest String With Swaps

Pattern: Graph | DSU (Union-Find) | Connected Components

Intuition

  • Treat each index as a node.
  • Every allowed swap (u, v) means both indices belong to the same component.
  • Use DSU to merge connected indices.
  • Characters within the same component can be rearranged freely.
  • Sort indices and their characters independently, then map them back.

Algorithm

  1. Initialize DSU with n elements.
  2. For every pair (u, v), perform union(u, v).
  3. Group indices by their DSU parent.
  4. For each component:
  5. Sort indices.
  6. Extract and sort corresponding characters.
  7. Assign sorted characters to sorted indices.

C++ Code

class Solution {
    vector<int> parent, sz;

    int find(int x) {
        if (parent[x] != x)
            parent[x] = find(parent[x]);
        return parent[x];
    }

    void unite(int a, int b) {
        a = find(a);
        b = find(b);

        if (a == b) return;

        if (sz[a] < sz[b]) swap(a, b);

        parent[b] = a;
        sz[a] += sz[b];
    }

public:
    string smallestStringWithSwaps(
        string s, vector<vector<int>>& pairs) {

        int n = s.size();

        parent.resize(n);
        sz.assign(n, 1);
        iota(parent.begin(), parent.end(), 0);

        // Merge connected indices
        for (auto& p : pairs)
            unite(p[0], p[1]);

        // Group indices by component
        unordered_map<int, vector<int>> groups;

        for (int i = 0; i < n; i++)
            groups[find(i)].push_back(i);

        // Sort characters within each component
        for (auto& [root, indices] : groups) {
            string chars;

            for (int idx : indices)
                chars += s[idx];

            sort(chars.begin(), chars.end());

            sort(indices.begin(), indices.end());

            for (int j = 0; j < indices.size(); j++)
                s[indices[j]] = chars[j];
        }

        return s;
    }
};

Complexity

Let N be the length of the string and M be the number of swap pairs. The function α(N) is the inverse Ackermann function.

  • Process swap pairs in O(M α(N)) time by calling unite() for each pair.
  • Group indices by component in O(N α(N)) time by calling find() for each index.
  • Sort within each component in O(N log N) total time. A component of size k takes O(k log k) to sort its indices and characters. The component sizes sum to N.

Overall time is O(N log N + M α(N)).
Auxiliary space is O(N) for the DSU, component groups, and temporary character storage.

Key Takeaways

  • DSU identifies connected components without building an adjacency list.
  • find() identifies the component representative.
  • union() merges two components.
  • Sorting ensures lexicographically smallest assignment.

Remember: Union → Group by Root → Sort → Reassign.