Skip to main content
All Questions

Implement Trie

Medium

Design a data structure that efficiently stores and retrieves strings. Specifically, implement a Trie (Prefix Tree) with the following operations:

  • insert(String word): Inserts a string word into the trie.
  • search(String word): Returns true if the string word is present in the trie (i.e., was inserted before), and false otherwise.
  • startsWith(String prefix): Returns true if there is any string in the trie that starts with the given prefix, and false otherwise.

Example

insert("apple") search("apple") -> true search("app") -> false startsWith("app") -> true insert("app") search("app") -> true

Constraints

  • All inputs are guaranteed to be lowercase English letters (a-z).
  • The length of the input string is in the range [1, 2000].
  • The total number of calls to insert, search, and startsWith is at most 3 * 10^4.

Related courses

Course

Machine Learning Engineer Interview Prep

Land your dream machine learning role at Meta, Google, Amazon, Apple, Microsoft, Nvidia, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Explore ML system design, core concepts, coding, behavioral interviews, and more.

Course

Data Engineering Interview Prep

Land your dream data engineering role at Meta, Google, Amazon, Microsoft, Walmart, DoorDash, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice data modeling, pipeline design, SQL, coding, behavioral interviews, and more.