InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Tries

Implement Trie (Prefix Tree)

medium Original ↗ 00:00

Problem

Build a data structure that stores a collection of lowercase strings and supports three operations:

  • Trie() — create an empty structure.
  • insert(word) — add word to the structure.
  • search(word) — return True if word was previously inserted as a complete word, False otherwise.
  • startsWith(prefix) — return True if any previously inserted word begins with prefix, False otherwise.

The distinction between search and startsWith matters: after inserting "apple", search("app") is False but startsWith("app") is True.

Examples

  • insert("apple"), then search("apple")True — the exact word was inserted.
  • After the above, search("app")False but startsWith("app")True"app" is only a prefix, not a stored word.
  • Then insert("app"), and now search("app")True — the prefix became a full word too.

Constraints

  • 1 <= len(word), len(prefix) <= 2000
  • All strings consist of lowercase English letters az only.
  • At most 3 * 10^4 calls total to insert, search, and startsWith.

Think about it first

Hint 1 Storing the words in a hash set makes search trivial — but how would you answer startsWith without scanning every stored word?
Hint 2 Words that share a prefix can share storage. Picture a tree where the root is the empty string and each edge is labeled with one letter; a word is the path of letters from the root.
Hint 3 Give each node a dict from letter to child node plus a boolean is_end. insert walks the path creating missing nodes and marks the last one; search and startsWith both walk the path, differing only in whether they check is_end at the end.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug