Canonicalize Search Terms Under Letter Equivalence Rules
Last updated: November 29, 2026
Quick Overview
Two equal-length strings a and b define letter equivalences: a[i] is equivalent to b[i], and equivalence is reflexive, symmetric, and transitive. Rewrite a query string so every letter is replaced by the smallest letter in its equivalence class.
0
0
0 solved
Two equal-length strings a and b define letter equivalences: a[i] is equivalent to b[i], and equivalence is reflexive, symmetric, and transitive. Rewrite a query string so every letter is replaced by the smallest letter in its equivalence class.
A Google screen question dressed as search normalization, where equivalent characters should map to one canonical form before indexing. The interviewer wants to see union-find over the 26 letters with the twist that the root is always the smallest member, so lookups return the answer directly.
What the Interviewer Expects
- Recognizes equivalence classes as union-find over letters
- Keeps the lexicographically smallest letter as each root
- Leaves characters outside the alphabet untouched
- Handles repeated or self-referential pairs
- Explains why the alphabet bound makes this trivially fast
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if the alphabet is all of Unicode?
- Support adding new equivalence rules between queries without recomputing everything.
- How would you produce, for each class, the full list of letters in it?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Input:
rule_a,rule_bof equal length, plus aquery. - Lowercase
atozparticipate in rules; any other character is copied unchanged. - Output: the query with each letter replaced by the ...
High-Level Design
Build a union-find over 26 letters. For each pair (rule_a[i], rule_b[i]) merge their sets, always attaching the larger root under the smaller one. That invariant means every root is the minimum of i...