IntermediateTreesStringsDesign

Implement Trie (Prefix Tree)

Problem

Design a data structure Trie supporting three operations: insert(word) adds a word, search(word) returns true if the exact word was previously inserted, and startsWith(prefix) returns true if any inserted word begins with prefix. All strings consist of lowercase English letters. The structure will receive up to 3·10^4 mixed operations.

Constraints
  • 1 ≤ word.length, prefix.length ≤ 2000
  • total operations ≤ 3·10^4
  • lowercase a–z only
Examples
in: insert("apple"); search("apple"); search("app"); startsWith("app"); insert("app"); search("app")
out: true, false, true, true
search("app") is false until "app" itself is inserted; startsWith("app") is true because "apple" exists.

What this tests

  • Choosing a structure whose cost depends on key length, not the number of keys
  • Distinguishing "is a word" from "is a prefix" with a terminal flag
  • Node representation trade-offs (array of 26 vs hash map)
  • Clear API design and complexity per operation
  • Talking through memory usage honestly
Problem ClarificationImplementationComplexity AnalysisCommunicationEdge Cases

Progressive hints

Choose how much help you want. Each hint reveals a little more; the pattern is not named until hint 2.

Hint 1Direction
Hint 2Pattern
Hint 3Data structure
Hint 4Algorithm
Hint 5Pseudocode
Solution

Solve in your language

The editor, starter code and solution adapt to the language you pick — C++, JavaScript, TypeScript or Python.

Solve in

Candidate thinking

How a strong candidate reasons through this problem, step by step.

Try the problem yourself first (or run the mock interview), then compare your process against a strong candidate's.

Follow-up engine

Requirements change; so does the right algorithm.

F1
Add delete(word).
F2
Return all words with a given prefix (autocomplete), or count them.
F3
Search with wildcards, e.g. "a.c" where . matches any letter.
F4
Memory is tight and words are long with little sharing. What would you change?

Related concepts