Skip to content
BytePatterns

Prefix Tree Operations

EasyTries#trie#design~20m

Problem

Build a prefix tree for lowercase words with three operations. insert(word) stores a word. has_word(word) reports whether exactly that word was stored. has_prefix(prefix) reports whether any stored word starts with the given non-empty prefix. Each operation should cost time proportional to the length of its argument, however many words are stored.

Examples

Input:  insert("apple"), has_word("apple"), has_word("app"), has_prefix("app")
Output: True, False, True
Why:    "app" begins a stored word but was never stored itself
Input:  insert("apple"), insert("app"), has_word("app")
Output: True
Input:  (nothing inserted), has_word("app"), has_prefix("a")
Output: False, False
Why:    edge case, an empty tree contains no words and no prefixes

Hints

0 / 3

Stuck on the idea rather than the code? Trie Basics covers it.