TRIE-P2

Counting words and prefixes

Practice 2 of 5Tries8 tests

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_prefix must 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1CountsNot run
2Remove one copyNot run
3Remove a missing wordNot run
4Removed completelyNot run
5Word inside a wordNot run
6Insert after removeNot run
7Many wordsNot run
820,000 wordsNot run