Implement an extensible prefix tree
Company: Anthropic
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates the ability to design and implement an extensible prefix tree (trie), covering competencies in Unicode-aware string handling, memory and time optimization, concurrency or thread-safety considerations, and support for operations like insert, search, startsWith, countPrefix and erase.
Constraints
- 1 <= len(operations) == len(arguments) <= 2 * 10^5
- Each operations[i] is one of insert, search, startsWith, countPrefix, or erase
- 0 <= len(arguments[i]) <= 10^3
- The sum of all argument lengths is at most 2 * 10^5
- Arguments may contain arbitrary Unicode characters, and duplicate words are allowed
Examples
Input: (['insert','insert','search','search','startsWith','countPrefix','erase','search','countPrefix','startsWith'], ['apple','app','apple','ap','ap','app','apple','apple','app','apple'])
Expected Output: [None, None, True, False, True, 2, True, False, 1, False]
Input: (['insert','insert','countPrefix','search','erase','search','countPrefix','erase','search','erase'], ['cat','cat','ca','cat','cat','cat','ca','cat','cat','cat'])
Expected Output: [None, None, 2, True, True, True, 1, True, False, False]
Hints
- Store two counters at each node: how many words pass through the node and how many words end there. This makes duplicates and countPrefix easy to support.
- During erase, record the path from the root to the terminal node. After decrementing counts, walk backward and delete child links whose pass count becomes zero.