Design a Multiset Trie with Fast Prefix Counting
Data Structure DesignModel answerLast 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 wordsearch(word)— return true if the word exists (at least one copy)count(word)— return the exact multiplicity of the wordstartsWith(prefix)— return true if any stored word begins with this prefixcountPrefix(prefix)— return the total number of stored words (counting duplicates) that begin with this prefixerase(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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining efficient prefix counts while supporting deletion. A standard trie stores one bit per node indicating whether a word ends there. We extend this by tracking two counters at each node:
pass_count: how many stored words (with multiplicity) include this node on their pathend_count: how many stored words end exactly at this node
This design makes countPrefix run in O(L) time—we traverse to the prefix's final node and return its pass_count—without needing to explore the entire subtree. Deletion becomes straightforward: decrement counts along the path, and prune any child whose pass_count drops to zero.
Core data structure
Each node holds a dictionary mapping characters to child nodes, plus the two counters. Using a dictionary instead of a fixed array makes the trie sparse and suitable for large alphabets like Unicode. Python's __slots__ reduces per-node memory overhead by eliminating the instance dictionary.
class _Node:
__slots__ = ("children", "pass_count", "end_count")
def __init__(self):
self.children = {} # char -> _Node
self.pass_count = 0
self.end_count = 0
Unicode normalization
Visually identical strings can differ at the byte level. For example, "é" can be represented as a single precomposed character (U+00E9) or as "e" followed by a combining acute accent (U+0301). To ensure consistent lookups, we normalize all input strings to Unicode NFC (Canonical Composition) form using Python's unicodedata.normalize. This is configurable: the constructor accepts a normalize parameter that defaults to "NFC" but can be set to None to disable normalization.
Thread safety
Python's GIL does not guarantee atomicity for compound operations. Two threads inserting the same word could both observe a missing child, each create a new node, and overwrite each other, corrupting counts. We guard all public methods with a single threading.Lock. This is simple and correct. For read-heavy workloads, a readers-writer lock would allow concurrent reads. For extremely read-heavy scenarios, a copy-on-write design—where writes produce a new root and swap it atomically—eliminates read contention entirely, though at the cost of higher memory usage during updates.
Implementation
import threading
import unicodedata
from typing import Optional
class _Node:
__slots__ = ("children", "pass_count", "end_count")
def __init__(self):
self.children = {}
self.pass_count = 0
self.end_count = 0
class Trie:
def __init__(self, normalize: Optional[str] = "NFC"):
self._root = _Node()
self._lock = threading.Lock()
self._normalize = normalize
def _norm(self, s: str) -> str:
if not isinstance(s, str):
raise TypeError("input must be a string")
return unicodedata.normalize(self._normalize, s) if self._normalize else s
def _traverse(self, s: str) -> Optional[_Node]:
"""Walk to the node representing string s, or None if path doesn't exist."""
node = self._root
for char in s:
node = node.children.get(char)
if node is None:
return None
return node
def insert(self, word: str) -> None:
word = self._norm(word)
with self._lock:
node = self._root
node.pass_count += 1
for char in word:
if char not in node.children:
node.children[char] = _Node()
node = node.children[char]
node.pass_count += 1
node.end_count += 1
def search(self, word: str) -> bool:
return self.count(word) > 0
def count(self, word: str) -> int:
word = self._norm(word)
with self._lock:
node = self._traverse(word)
return node.end_count if node else 0
def startsWith(self, prefix: str) -> bool:
return self.countPrefix(prefix) > 0
def countPrefix(self, prefix: str) -> int:
prefix = self._norm(prefix)
with self._lock:
node = self._traverse(prefix)
return node.pass_count if node else 0
def erase(self, word: str) -> bool:
"""Remove one copy of word. Return False if not present."""
word = self._norm(word)
with self._lock:
target = self._traverse(word)
if target is None or target.end_count == 0:
return False
# Decrement counts along path; prune when a node becomes unused
node = self._root
node.pass_count -= 1
for char in word:
child = node.children[char]
child.pass_count -= 1
if child.pass_count == 0:
# No remaining words use this subtree
del node.children[char]
return True
node = child
# Path still in use; just decrement end count
node.end_count -= 1
return True
Correctness
The invariant is: for any node, pass_count equals the total multiplicity of all stored words whose paths pass through or end at that node. end_count equals the multiplicity of the exact string represented by the path to that node.
Insert increments pass_count on every node along the word's path, including the root (which counts all words), and increments end_count once at the final node.
Erase first verifies the word exists by checking both that the path exists and that end_count > 0. This prevents corrupting counts when erasing a non-existent word. It then decrements pass_count along the path. When a child's pass_count hits zero, no remaining word uses that node or anything below it, so we delete the child and terminate early. If we reach the end without pruning, we decrement end_count at the final node.
Queries simply traverse to the relevant node and read the appropriate counter.
Complexity
Let L be the length of the input string in characters, and N be the total number of characters across all distinct stored paths.
| Operation | Time | Space |
|---|---|---|
insert | O(L) | O(L) worst case for new path |
search, count | O(L) | O(1) |
startsWith, countPrefix | O(L) | O(1) |
erase | O(L) | O(1), may free nodes |
Overall space is O(N). Dictionary lookups are expected O(1) under uniform hashing assumptions. Unicode normalization adds O(L) time and allocates a new string.
Edge cases and testing
- Empty string: Valid as a word.
countPrefix("")returns the total count of all stored words. - Duplicates: Inserting
"cat"three times and erasing once leaves two copies.count("cat")returns 2. - Erase non-existent: Returns false, does not corrupt structure.
- Unicode variants:
"café"as precomposed vs. decomposed must match after normalization. - Concurrent modifications: Spawn threads that insert/erase the same words; verify final counts match expected results.
- Memory leaks: Insert many words, erase all, verify memory is released (measure node count or use a memory profiler).
Comparison to alternatives
Hash table: O(1) insert/search but no prefix operations. Would need a separate structure or expensive iteration to answer countPrefix.
Balanced tree (e.g., sorted map): O(L log N) insert/search. Prefix queries require iterating a range, which is O(K + L log N) for K matching words. Slower than the trie's O(L) for both insert and prefix queries when prefixes are common.
Radix tree (compressed trie): Stores edges as string chunks instead of single characters. Reduces node count when paths are sparse, improving memory. Complicates insertion and deletion logic. Good for static datasets or when paths share long common prefixes.
The trie excels when prefix queries are frequent, the alphabet is large (like Unicode), and the dataset is dynamic with inserts and deletes.