Problem 448776 · medium · Level 04 Non-Linear Data Structures

A Prefix Tree for Autocomplete

trie · dictionaries · classes · strings

A trie (prefix tree) stores strings character by character so that all words sharing a prefix share a path. It powers autocomplete, spell-checkers and IP routing: checking whether any stored word starts with a prefix costs only O(len(prefix)), no matter how many words are stored.

Build the word store behind a search box's autocomplete as a class Trie:

  • Trie() starts with no words.
  • insert(word) adds word to the store.
  • search(word) answers True only if word itself was inserted earlier, and False otherwise.
  • starts_with(prefix) answers True if at least one inserted word begins with prefix, and False otherwise. Every word begins with itself, so after insert("cat") the call starts_with("cat") is True.

Examples

Input:
  Trie()
  insert("plan")
  insert("planet")
  search("plane")       -> False   (so far only a prefix of "planet")
  starts_with("plane")  -> True
  search("plan")        -> True
  starts_with("plot")   -> False
  insert("plane")
  search("plane")       -> True
Output: [None, None, None, False, True, True, False, None, True]

Constraints

  • Words and prefixes consist of lowercase letters, length 1..100
  • At most 1000 calls in total

Goals

  • Represent a trie as nested dictionaries, one level per character
  • Mark the end of a word separately from the existence of a prefix
  • Share a private helper between two public methods
Starting Python…