progress

~/problems / Tries

Count words by prefix with a trie

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Implement class PrefixCounter, a trie that remembers how many words pass through each node:

  • PrefixCounter() starts empty.
  • add(word) stores word (lowercase letters, length >= 1). Adding a word again counts it twice.
  • count(prefix) returns how many stored words start with prefix. The empty prefix "" matches every word.
p = PrefixCounter()
for w in ["tea", "ten", "to", "tea"]:
    p.add(w)
p.count("te")     # 3   ("tea" twice, "ten")
p.count("tea")    # 2   (a whole word is also a prefix of itself)
p.count("teas")   # 0
p.count("")       # 4
A trie of tea, ten, to and tea again, each node showing how many words pass through it; the node reached by t then e holds 3, the answer to count("te")

Use nested dicts as nodes (letter to child, plus a counter under a key like "#"), or a small Node class.

⭐ Bonus: a speed test with 20,000 words and 20,000 questions earns a star if both methods cost O(length of the argument) instead of comparing against every word.

Show hint

add adds 1 to the root, then walks down creating missing children with setdefault, adding 1 to each node it steps into (the root's count is how count("") sees every word); count walks the same path and returns the last node's count, or 0 when a letter is missing.

Topic: Trie. Prefix tree; longest-match tokenizing.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc