Lexicographically Smallest Equivalent Substring

Oh hey, it's disjoint set union.

None.cpp

_42
_42
class Solution {
_42
public:
_42
string smallestEquivalentString(string s1, string s2, string baseStr) {
_42
// for each letter, what is the lexicographically smallest equivalent letter?
_42
array<int, 26> dsu;
_42
for (int& i : dsu) i = -1;
_42
_42
const int n = s1.size();
_42
_42
auto find = [&] (int i) {
_42
while (dsu[i] >= 0) {
_42
i = dsu[i];
_42
}
_42
return i;
_42
};
_42
_42
auto unify = [&] (int i, int j) {
_42
int pi = find(i);
_42
int pj = find(j);
_42
if (pi==pj) return;
_42
_42
if (pi < pj) {
_42
dsu[pj] = pi;
_42
} else {
_42
dsu[pi] = pj;
_42
}
_42
};
_42
_42
unordered_map<char, set<char>> equiv;
_42
for (int i = 0; i < n; i++) {
_42
unify(s1[i] - 'a', s2[i] - 'a');
_42
}
_42
_42
string res {};
_42
for (char c : baseStr) {
_42
res.push_back(find(c-'a') + 'a');
_42
}
_42
_42
return res;
_42
}
_42
};

If you found this solution helpful, consider leaving a star!