Replace Words in Reviews With Their Shortest Catalog Root

Last updated: November 29, 2026

Quick Overview

Given a list of root terms and a sentence, replace each word in the sentence with the shortest root that is a prefix of it, leaving words with no matching root unchanged.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Online Assessment
Coding & Algorithms
Medium

0

0

0 solved


Given a list of root terms and a sentence, replace each word in the sentence with the shortest root that is a prefix of it, leaving words with no matching root unchanged.

An online assessment style question in Amazon's style, framed around normalizing review text by collapsing inflected words (`charging`, `charger`) to catalog roots before indexing. It checks that you build a trie once and stop at the first terminal while scanning each word.

What the Interviewer Expects
  • Builds a trie of roots once
  • Stops at the first end-of-root node for the shortest match
  • Leaves unmatched words intact
  • Avoids O(words x roots) prefix checks
  • Handles roots that are prefixes of other roots
Key Topics to Cover
tries
prefix search
string processing
text normalization
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
  • How would you pick the longest root instead?
  • What if roots arrive and expire while the system is running?
  • How would you do this for a 10 GB review dump?
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

Roots and words are lowercase. If several roots are prefixes of a word, use the shortest. Words are separated by single spaces; output preserves that....

High-Level Design

Checking every root against every word with startswith costs O(W⋅R⋅L)O(W \cdot R \cdot L). Instead insert all roots into a trie with an end marker. For each word, walk the trie character by character: the...


Submit Your Answer
Markdown supported