Implement class PrefixCounter, a trie that remembers how many words pass through each node:
PrefixCounter()starts empty.add(word)storesword(lowercase letters, length >= 1). Adding a word again counts it twice.count(prefix)returns how many stored words start withprefix. 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
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.