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.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

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
Union-Find
Equivalence Classes
Strings
Canonical Forms
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample Answer
Requirements
  • Input: rule_a, rule_b of equal length, plus a query.
  • Lowercase a to z participate 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...


Submit Your Answer
Markdown supported