← All Exercises
Trie with Prefix Counting
intermediatepython
Background
Tries trade memory for predictable O(length) lookups and make shared prefixes explicit, which powers autocomplete and prefix filters.
Problem
Implement a Trie class with insert(word), contains(word), and count_prefix(prefix). Words must be non-empty lowercase alphabetic strings; duplicate insertions are ignored, and prefix counts include every inserted word that starts with that prefix.
Input
A list of lowercase words to insert and a list of lowercase prefixes to query.
Output
A list of prefix counts in query order.
Sample tests
Sample 1
Input: words = ['apple', 'app', 'apply'], prefixes = ['app', 'appl', 'b']
Expected: [3, 2, 0]
Sample 2
Input: words = ['go', 'go', 'gopher'], prefixes = ['go', 'g']
Expected: [2, 2]
Your solution
Learning objective
Use trie node counters for O(prefix length) prefix queries and O(word length) insertion.