Skip to main content

Implement Trie

MediumPremium

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.

A Trie is a tree-like data structure that stores strings, where each node represents a single character of the string. This structure allows for efficient search operations by traversing down the branches of the tree, making it suitable for tasks like auto-completion, dictionary lookups, and spell checking.

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.