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
- Initialize DSU with
nelements. - For every pair
(u, v), performunion(u, v). - Group indices by their DSU parent.
- For each component:
- Sort indices.
- Extract and sort corresponding characters.
- 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 callingunite()for each pair. - Group indices by component in
O(N α(N))time by callingfind()for each index. - Sort within each component in
O(N log N)total time. A component of sizektakesO(k log k)to sort its indices and characters. The component sizes sum toN.
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.