← All Exercises

Word Dictionary with a Prefix Trie

intermediatepython~25min

Background

Trie-backed dictionaries power autocomplete, spell check, and routing tables with shared prefix storage.

Problem

Build a word dictionary that supports add_word, search for exact words, and starts_with for prefixes, then return the boolean result of each query in order.

Input

A list of words to insert and a list of [kind, text] queries where kind is search or prefix.

Output

A list of booleans, one per query, in the same order as the queries.

Sample tests

Sample 1

Input: words = ["apple","app"], queries = [["search","app"],["search","ap"],["prefix","app"],["prefix","banana"]]
Expected: [True, False, True, False]

Sample 2

Input: words = ["car","card"], queries = [["prefix","ca"],["search","card"],["search","care"]]
Expected: [True, True, False]

Sample 3

Input: words = [], queries = [["search","a"]]
Expected: [False]

Your solution

Learning objective

Separate path existence from word termination and implement trie insert and lookup iteratively.