Lexicographically Smallest Equivalent String, explained
Lexicographically Smallest Equivalent String is a union-find problem over the 26 letters: pair up first[i] with second[i], and whenever two classes merge, make the alphabetically smaller root the parent. Then every letter's root is the smallest letter it is equivalent to, so you rewrite the base string by replacing each character with its root, in O(m + b) time, because a structure with only 26 nodes keeps every find short.
By Evin JohnPublished 7 min read
What you are asked to do
You receive two strings of the same length, first and second, plus a third string called base. For every position i, the letters first[i] and second[i] are declared equivalent. Equivalence behaves the way you expect: every letter is equivalent to itself, the relation works in both directions, and it chains, so if a matches b and b matches c then a matches c. For each character of base, replace it with the alphabetically smallest letter it is equivalent to, and return the new string.
| first | second | base | Result | Classes that matter |
|---|---|---|---|---|
| rope | mild | porter | limtdm | {m, r}, {i, o}, {l, p}, {d, e} |
| dog | cat | good | gaac | {c, d}, {a, o}, {g, t} |
| abc | bcd | zebra | zeara | {a, b, c, d} chained through overlaps |
| xx | yy | xyz | xxz | {x, y}; z is untouched |
| aa | aa | hello | hello | Only self-pairs, nothing changes |
The abc and bcd row is the one that trips people. No position pairs a with d directly, but a~b, b~c and c~d chain together, so d becomes a. Letters of base that never appear in first or second, like z here, simply stay as they are.
Why it gets asked
This is a compact test of whether you recognize an equivalence relation and know the data structure built for it. It also adds one twist to plain union-find: you need the smallest member of each class, not just any representative. Candidates who know union-find well usually see that they can make the smallest letter the root, so the representative is the answer. Candidates who do not often end up with a separate pass to compute minimums, which works but takes longer to explain.
Simple approach: propagate the smallest label
Start with every letter labeled as itself. Sweep over the pairs; for each pair, set both labels to the smaller of the two. Repeat full sweeps until a sweep changes nothing. Labels only ever decrease, and each is always a letter from the same class, so at the end every letter carries the smallest member of its class.
def smallest_equivalent_slow(first, second, base):
best = {chr(c): chr(c) for c in range(ord("a"), ord("z") + 1)}
changed = True
while changed:
changed = False
for x, y in zip(first, second):
low = min(best[x], best[y])
if best[x] != low or best[y] != low:
best[x] = best[y] = low
changed = True
return "".join(best[ch] for ch in base)Be honest about this one in an interview: with only 26 letters it is not actually slow, since each full sweep pushes the smallest label at least one more step along every chain, and no chain of distinct letters is longer than 25 steps. The cost is that the idea depends on a tiny alphabet. If the interviewer swaps letters for arbitrary integers or user ids, the number of sweeps grows with the longest chain, and you want a structure that handles merges directly.
Main approach: union-find where the smallest letter wins
Map a to 0 through z to 25 and give each letter a parent pointer to itself. For each position, find the roots of the two letters. If they differ, attach the larger root under the smaller one. That single rule maintains an invariant: the root of every class is the smallest letter in it. When two classes merge, the new root is the smaller of the two old roots, and each old root was already the smallest in its own class, so the new root is the smallest overall.
After processing every pair, each character of base maps to find(character). Notice that we give up union by size to keep this rule. With 26 nodes that costs nothing, and path compression, if you add it, keeps finds short anyway.
def smallest_equivalent(first, second, base):
head = list(range(26))
def find(x):
while head[x] != x:
x = head[x]
return x
for x, y in zip(first, second):
rx, ry = find(ord(x) - ord("a")), find(ord(y) - ord("a"))
if rx < ry:
head[ry] = rx
elif ry < rx:
head[rx] = ry
return "".join(chr(find(ord(ch) - ord("a")) + ord("a")) for ch in base)function smallestEquivalent(first, second, base) {
const head = Array.from({ length: 26 }, (_, i) => i);
const find = (x) => {
while (head[x] !== x) {
head[x] = head[head[x]];
x = head[x];
}
return x;
};
const A = 97; // char code of "a"
for (let i = 0; i < first.length; i++) {
const rx = find(first.charCodeAt(i) - A);
const ry = find(second.charCodeAt(i) - A);
if (rx !== ry) head[Math.max(rx, ry)] = Math.min(rx, ry);
}
return Array.from(base, (ch) => String.fromCharCode(find(ch.charCodeAt(0) - A) + A)).join("");
}The Python find skips compression on purpose to show it is optional at this size; the JavaScript one halves paths. Either is fine. Path halving rewires only non-root pointers, so it never disturbs the smallest-root invariant.
Trace
With first = abc and second = bcd: pair (a, b) has roots a and b, so b points to a. Pair (b, c): b's root is a, c's root is c, so c points to a. Pair (c, d): c's root is a, d's root is d, so d points to a. Now base zebra maps z to z, e to e, b to a, r to r and a to a, giving zeara.
Complexity summary
| Approach | Time | Memory | Scales to large alphabets? |
|---|---|---|---|
| Label sweeps | O(26 · m) here, O(k · m) for k letters | O(26) | Poorly |
| Graph search per letter of base | O(b · (26 + m)) | O(26 + m) | Wasteful, repeats work |
| Union-find, smallest root | O(m + b), finds bounded by 26 nodes | O(26) | Yes, with any ordered labels |
Inputs worth testing
- A letter paired with itself, like (a, a): a no-op.
- A pair that is already connected through earlier pairs: find returns the same root, nothing changes.
- Characters in base that never appear in the pairs: they map to themselves.
- Long chains that reach a small letter late, like (y, z), (x, y), ..., (a, b): every letter ends at a.
- Empty first and second: the base comes back unchanged.
Mistakes candidates make
- Attaching first[i]'s root under second[i]'s root regardless of order, then returning the root. The root is then not the smallest letter.
- Comparing the letters themselves instead of their roots when choosing the parent.
- Applying only direct pairs and missing chains, which gives b for d in the abc and bcd example.
- Rewriting base during the union pass, before all pairs are known.
- Adding union by rank and keeping the smallest-root rule at the same time without tracking the minimum separately. Pick one rule or store a min per root.
How it might sound
Fictional example
- Candidate
- The pairs define an equivalence relation on letters, so I will use union-find with 26 nodes.
- Candidate
- When I merge two classes I always hang the larger root under the smaller one. That keeps the root equal to the smallest letter in its class, so find gives me the answer for any character.
- Candidate
- Then I map each character of the base string through find. It is linear in the input, since the structure never has more than 26 nodes.
Related problems
Smallest String With Swaps also asks for the smallest string, but there the sets are positions and you sort letters inside each set. Number of Good Paths uses union-find more aggressively, merging tree nodes in order of their values. The data structure interview questions guide covers union-find alongside other common structures.
Using Natively to practice
Natively can pick up a problem like this from a screenshot during practice and suggest code and an explanation; it is most useful as a comparison once you have tried the smallest-root idea yourself. It keeps a transcript of each mock round on your computer, so you can check whether you stated the invariant clearly. See how an AI interview assistant works on Mac and Windows.
Questions people ask
How do you solve Lexicographically Smallest Equivalent String?
Build union-find over the 26 letters. For each position, union first[i] and second[i], always attaching the larger root under the smaller one. Then replace each character of the base string with its root.
Why attach the larger root under the smaller one?
It keeps an invariant: the root of every class is its smallest letter. That way find returns the answer directly, with no separate pass to compute minimums.
What is the time complexity?
Linear in the input, O(m + b) for m pairs and a base string of length b, because the structure never has more than 26 nodes. Extra space is O(26).
What happens to letters that never appear in the pairs?
They are only equivalent to themselves, so they stay unchanged in the output.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
