KatInterview

Design a Multiset Trie with Fast Prefix Counting

Data Structure DesignModel answer
MediumModel answerData Structure Designtriedata-structuresconcurrency

Last updated

Build a trie that tracks word multiplicities, supports insertion, deletion, exact and prefix lookup, and handles Unicode safely.

Design and implement a trie (prefix tree) that behaves as a multiset over strings. Your implementation must support these operations:

  • insert(word) — add one occurrence of the word
  • search(word) — return true if the word exists (at least one copy)
  • count(word) — return the exact multiplicity of the word
  • startsWith(prefix) — return true if any stored word begins with this prefix
  • countPrefix(prefix) — return the total number of stored words (counting duplicates) that begin with this prefix
  • erase(word) — remove one occurrence of the word; return false if it was not present

Your design should:

  • Handle arbitrary Unicode strings correctly
  • Optimize for both time and space
  • Be safe for concurrent access from multiple threads, or clearly document any restrictions
  • Prune unused nodes when words are deleted

Provide the time and space complexity for each operation. Discuss how you would test the implementation, including edge cases like empty strings, duplicate insertions, erasing non-existent words, and Unicode normalization. Compare your design to alternative approaches like hash tables or balanced search trees.

Hints

Hint 1

Store a count at each node representing how many words pass through it; this makes prefix counting efficient without traversing the entire subtree.

Hint 2

When erasing a word, decrement counts along its path and remove any child whose count reaches zero to avoid memory leaks.

Hint 3

Unicode strings can have multiple byte-level representations for the same visual character; normalizing to a canonical form prevents lookup inconsistencies.