KatInterview

Word Dictionary with Insert and Query Operations

Data Structure DesignAuto-graded · 20 test cases
MediumAuto-gradedData Structure Designtriedata-structuresstring-matching

Last updated

Tests implementing a character-level trie to handle insert, exact-match lookup, and prefix-existence queries while distinguishing complete words from prefixes.

Implement a dictionary for lowercase English words that handles three types of operations in sequence:

  • ["insert", w]: store word w in the dictionary
  • ["search", w]: check whether word w exists in the dictionary
  • ["prefix", p]: check whether any stored word begins with string p

Given a list of operations, execute them in order and return a list of boolean results for every search and prefix query, preserving their original order.

Rules

  • The dictionary begins empty.
  • Each operation is a two-string list: the command type followed by a word or prefix string.
  • insert commands produce no output. Re-inserting a word that already exists has no effect.
  • search returns true only when the exact word was previously inserted; a string that is merely a prefix of a stored word returns false.
  • prefix returns true when at least one stored word starts with the given string, including the case where a stored word exactly equals the prefix string.
  • Each query reflects only the words inserted before that query.
  • If no search or prefix operations appear, return an empty list.

Constraints

  • 1 ≤ len(operations) ≤ 2 × 10⁴
  • Each operation type is one of "insert", "search", or "prefix"
  • Each word and prefix string has length in [1, 100] and contains only lowercase letters a–z

Examples

Example 1

Input: process_word_dictionary([['insert', 'card'], ['search', 'car'], ['prefix', 'car'], ['insert', 'car'], ['search', 'car'], ['search', 'cards']])

Output: [False, True, True, False]

Example 2

Input: process_word_dictionary([['prefix', 'a'], ['insert', 'a'], ['prefix', 'a'], ['search', 'a'], ['search', 'ab']])

Output: [False, True, True, False]

Example 3

Input: process_word_dictionary([['insert', 'x']])

Output: []

Hints

Hint 1

A trie (prefix tree) naturally separates the concept of 'a path exists' from 'a word ends here'.

Hint 2

Mark the final node of each inserted word with a special flag to distinguish complete words from intermediate prefixes.

Hint 3

Both search and prefix queries walk the same path character by character; they differ only in what they check at the end.