The problem
Write a trie that stores words with repeats, and counts them. insert(word) adds one copy of a word. count(word) returns how many copies of the word are stored. count_prefix(prefix) returns how many stored words start with the prefix, counting every copy. remove(word) removes one copy and returns True; if no copy is stored it changes nothing and returns False.
t = CountingTrie()
t.insert("apple"); t.insert("apple"); t.insert("app")
t.count("apple") # 2
t.count_prefix("ap") # 3
t.remove("apple") # True
t.count_prefix("ap") # 2
t.remove("ap") # False: ap was never inserted
Words and prefixes are non-empty and use the letters a to z.
Limits
- Up to 20,000 inserts, 10,000 removes and 25,000 counts, words of at most 6 letters. Every operation should take O(L) time:
count_prefixmust not visit the words below the prefix one by one.
Builds on TRIE-2 Insert, search and delete.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Counts | Not run | |
| 2 | Remove one copy | Not run | |
| 3 | Remove a missing word | Not run | |
| 4 | Removed completely | Not run | |
| 5 | Word inside a word | Not run | |
| 6 | Insert after remove | Not run | |
| 7 | Many words | Not run | |
| 8 | 20,000 words | Not run |