← DiffPush

Implement Trie II (Prefix Tree with Counts)

Standard Bar Tries · Problems O(L) per operation · O(total inserted characters)

The Badge Log Frequency Board

A security desk archives every badge word swiped at the gate and must answer tally questions on the fly: how many times was this exact badge word swiped, and how many archived words start with this fragment? Erasing removes one archived occurrence. The desk needs a structure that keeps per-word and per-prefix running tallies.

Input: A list of operations: ["Trie"], ["insert", word], ["countWordsEqualTo", word], ["countWordsStartingWith", prefix], or ["erase", word].

Output: Return one entry per count operation; all other operations yield null.

Constraints

Examples

Example 1

Input: {"ops":[["Trie"],["insert","apple"],["insert","apple"],["countWordsEqualTo","apple"],["countWordsStartingWith","app"],["erase","apple"],["countWordsEqualTo","apple"],["countWordsStartingWith","app"]]}
Output: [null,null,null,2,2,null,1,1]
Two inserts tally to 2; one erase drops both counts to 1.

Example 2

Input: {"ops":[["Trie"],["insert","badge"],["countWordsEqualTo","bad"],["countWordsStartingWith","bad"],["erase","badge"],["countWordsStartingWith","bad"]]}
Output: [null,null,0,1,null,0]
The prefix matches the stored word, but the shorter word itself was never archived.

Solve this in your browser →

Also on LeetCode ↗