Build a Trie That Counts Exact Matches and Prefixes With Deletion

Last updated: November 29, 2026

Quick Overview

Implement a trie for search-log terms with `insert(word)`, `count_equal(word)`, `count_prefix(prefix)`, and `erase(word)`, where the same word may be inserted multiple times and erase removes one occurrence.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Technical Screen
Coding & Algorithms
Medium

0

0

0 solved


Implement a trie for search-log terms with `insert(word)`, `count_equal(word)`, `count_prefix(prefix)`, and `erase(word)`, where the same word may be inserted multiple times and erase removes one occurrence.

A technical-screen design-a-structure question in Amazon's style, framed around counting how many logged queries start with a typed prefix. The interviewer wants per-node counters rather than subtree walks, and a correct erase that keeps counts consistent and prunes empty nodes.

What the Interviewer Expects
  • Stores a pass-through count and an end count on each node
  • Makes count_prefix O(length of prefix)
  • Handles duplicate inserts
  • Erase decrements along the path and prunes zero-count nodes
  • Handles erase of a word that is not present safely
Key Topics to Cover
tries
design a data structure
counting
memory
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 return the top 3 most frequent completions for a prefix?
  • How would you make this thread-safe for concurrent inserts?
  • How much memory does this use for 100 million queries and how would you shrink 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

Four operations on lowercase strings (spaces allowed). Duplicates count separately. erase removes one occurrence and is a no-op returning False if the word is absent. Prefix count includes exact mat...

High-Level Design

Each node holds passes (how many inserted words go through or end at this node) and ends (how many end exactly here). Then count_prefix is a walk plus one read, and count_equal the same with `...


Submit Your Answer
Markdown supported