Generate Every Query Rewrite From Transitive Synonym Pairs
Last updated: November 29, 2026
Quick Overview
Given synonym pairs where synonymy is transitive, and a search query of space-separated words, return every rewrite of the query obtained by replacing each word with any word in its synonym class, in sorted order.
0
0
0 solved
Given synonym pairs where synonymy is transitive, and a search query of space-separated words, return every rewrite of the query obtained by replacing each word with any word in its synonym class, in sorted order.
Query rewriting is core to Google Search recall, and this onsite question combines union-find with backtracking. The interviewer checks that you build classes once, avoid the trap of only applying direct synonyms, and reason about output size, which is the product of class sizes.
What the Interviewer Expects
- Builds synonym classes with union-find so transitivity is handled
- Precomputes sorted member lists per class
- Leaves words without synonyms as single options
- Generates the Cartesian product with backtracking
- Explains that output size dominates runtime
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
- Cap the output at the top k rewrites by a per-word score; how do you avoid generating everything?
- What if synonyms are context dependent, like 'apple' the fruit and the company?
- How would you serve this with low latency for live traffic?
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: list of word pairs and a query string.
- Synonymy is transitive and symmetric; words outside all pairs map only to themselves.
- Output: all distinct rewrites, sorted lexicographically....
High-Level Design
First, union every pair and group words by root, sorting each class. For each query word, its options are its class (if it appears in any pair) or just itself. The rewrites are the Cartesian product o...