Stem Every Word in a Document to Its Shortest Known Root
Last updated: November 29, 2026
Quick Overview
Given a dictionary of word roots and a sentence, replace each word that starts with some root by the shortest such root and return the rewritten sentence.
0
0
0 solved
Given a dictionary of word roots and a sentence, replace each word that starts with some root by the shortest such root and return the rewritten sentence.
A light Google phone screen warm-up tied to text normalization for indexing, where words like "running" map to a stem before lookup. The interviewer checks that you stop at the first terminal node rather than testing every root against every word.
What the Interviewer Expects
- Insert roots into a trie with an end marker
- Walk each word and stop at the first root end
- Keep the original word when no root matches
- Explain why this beats checking every root with startswith
- Rebuild the sentence with single spaces
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 you need the longest root rather than the shortest?
- How would you handle uppercase and punctuation?
- How would you do this on a stream of documents across many machines?
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: roots, a list of lowercase strings, and sentence, lowercase words separated by single spaces. Output: the sentence where each word is replaced by the shortest root that is a prefix of it, o...
High-Level Design
A naive approach checks each word against each root with startswith, which costs roughly words x roots x length. Instead build a trie of roots and mark nodes where a root ends. For each word, walk...