Lexicographically Smallest Equivalent String (LeetCode 1061): Solution and Explanation
Pairs of letters are declared equivalent. Rewrite a base string using the smallest equivalent letter at every position.
Intuition
Each column s1[i], s2[i] says two letters are interchangeable, and interchangeability chains: if a ~ c and c ~ e, then a ~ e. So the pairs split the 26 letters into classes, which is exactly what union-find tracks.
Every position of baseStr can be replaced on its own, without affecting the others. To make the whole string as small as possible, make each position as small as possible: use the smallest letter in that character's class.
Union-find can hand us that letter for free. When two classes merge, always keep the smaller root. Then the root of every class is its smallest member, and find(c) is the answer for c.
With only 26 letters, the forest stays tiny, so each find is effectively constant time.
Approach: Union-find with smallest-letter roots
- Create
parentof size 26 withparent[x] = x. - For each index
i, computera = find(s1[i])andrb = find(s2[i]). - If
ra < rb, setparent[rb] = ra; otherwise setparent[ra] = rb. The smaller letter stays the root. - Build the answer by replacing each character
cofbaseStrwithfind(c). - Return the built string.
Step-by-step example
s1 = "parker", s2 = "morris", baseStr = "parser"
- p ~ m: m is smaller, so m becomes the root of {m, p}. a ~ o: a becomes the root of {a, o}.
- r ~ r changes nothing. k ~ r: k is smaller, so {k, r} has root k.
- e ~ i: e becomes the root of {e, i}. r ~ s: find(r) = k, and k < s, so s joins {k, r, s}.
- Map "parser": p to m, a to a, r to k, s to k, e to e, r to k. The answer is "makkek".
Code: Python, Java, C++
1class Solution:
2 def smallestEquivalentString(self, s1: str, s2: str, baseStr: str) -> str:
3 parent = list(range(26))
4
5 def find(x):
6 while parent[x] != x:
7 parent[x] = parent[parent[x]]
8 x = parent[x]
9 return x
10
11 for a, b in zip(s1, s2):
12 ra, rb = find(ord(a) - 97), find(ord(b) - 97)
13 if ra < rb:
14 parent[rb] = ra
15 else:
16 parent[ra] = rb
17 return ''.join(chr(find(ord(c) - 97) + 97) for c in baseStr)1class Solution {
2 private int[] parent = new int[26];
3
4 private int find(int x) {
5 while (parent[x] != x) {
6 parent[x] = parent[parent[x]];
7 x = parent[x];
8 }
9 return x;
10 }
11
12 public String smallestEquivalentString(String s1, String s2, String baseStr) {
13 for (int i = 0; i < 26; i++) parent[i] = i;
14 for (int i = 0; i < s1.length(); i++) {
15 int ra = find(s1.charAt(i) - 'a'), rb = find(s2.charAt(i) - 'a');
16 if (ra < rb) parent[rb] = ra;
17 else parent[ra] = rb;
18 }
19 StringBuilder sb = new StringBuilder();
20 for (char c : baseStr.toCharArray()) sb.append((char) ('a' + find(c - 'a')));
21 return sb.toString();
22 }
23}1class Solution {
2 int parent[26];
3
4 int find(int x) {
5 while (parent[x] != x) {
6 parent[x] = parent[parent[x]];
7 x = parent[x];
8 }
9 return x;
10 }
11
12public:
13 string smallestEquivalentString(string s1, string s2, string baseStr) {
14 for (int i = 0; i < 26; i++) parent[i] = i;
15 for (int i = 0; i < (int) s1.size(); i++) {
16 int ra = find(s1[i] - 'a'), rb = find(s2[i] - 'a');
17 if (ra < rb) parent[rb] = ra;
18 else parent[ra] = rb;
19 }
20 string res;
21 for (char c : baseStr) res += (char) ('a' + find(c - 'a'));
22 return res;
23 }
24};Time and space complexity
O(n + m)
There are n unions and m lookups, each a find on a forest of at most 26 nodes with path compression, so each is effectively constant time.
O(1)
The parent array has 26 entries. The output string of length m is not counted as extra space.
Other approaches
Graph plus DFS per class (time O(n + m), space O(1))
Build an undirected graph on the letters, run a DFS from each unvisited letter to collect its component, and record the minimum letter of each component. Same result, a little more code.
Union-find with a separate minimum array (time O(n + m), space O(1))
Use ordinary union by size and keep min[root] updated on every merge. It works, but forcing the smaller root to win removes the extra array.
Common mistakes
- Linking letters instead of roots, as in parent[s2[i]] = s1[i]. That can detach a letter from a class it already joined and lose an equivalence.
- Letting the larger root win a merge. find(c) then returns some member of the class, not necessarily the smallest.
- Assuming s1 holds the smaller letter of each pair. The pair is symmetric, so compare the two roots every time.
- Translating baseStr through parent[c] instead of find(c). parent[c] may point to an intermediate letter that is not the root.
Frequently asked questions
Why is replacing each character independently optimal?
Lexicographic order compares the first position where two strings differ. Making every position as small as possible gives a string that is no larger than any other option at every position, so it is the smallest overall.
Why does the smaller root always win?
If every merge keeps the smaller of the two roots, then by induction each root is the smallest letter in its class. That turns find(c) into a lookup of the best replacement for c.
What about letters that never appear in s1 or s2?
They stay in their own class of size one, so find returns the letter itself and it is copied into the answer unchanged.
What is the time complexity?
O(n + m) time, where n is the length of s1 and m is the length of baseStr, and O(1) extra space for the 26-entry parent array.