Problem
Ask
Submissions

Problem: Implement Trie

Medium
30 min
Explore how to implement a trie prefix tree to efficiently store and query strings. Learn to build functions that insert words, search complete words, and detect prefixes. This lesson helps you understand prefix trees for optimized search operations in coding interviews.

Statement

Trie is a tree-like data structure used to store strings. The tries are also called prefix trees because they provide very efficient prefix-matching operations. Implement a trie data structure with three functions that perform the following tasks:

  • Insert (word): This inserts a word into the trie.

  • Search (word): This searches the given word in the trie and returns TRUE if the complete word is found (i.e., all characters match and the last node is marked as the end of a word). Otherwise, return FALSE.

  • Search prefix (prefix): This searches the given prefix in the trie and returns TRUE if the prefix path exists in the trie (i.e., all prefix characters match), regardless of whether the last node is marked as the end of a word. Otherwise, return FALSE.

Constraints:

  • 11 \leq word.length, prefix.length 500\leq 500

  • The strings consist only of lowercase English letters.

  • At most, 10310^3 calls in total will be made to the functions.

Problem
Ask
Submissions

Problem: Implement Trie

Medium
30 min
Explore how to implement a trie prefix tree to efficiently store and query strings. Learn to build functions that insert words, search complete words, and detect prefixes. This lesson helps you understand prefix trees for optimized search operations in coding interviews.

Statement

Trie is a tree-like data structure used to store strings. The tries are also called prefix trees because they provide very efficient prefix-matching operations. Implement a trie data structure with three functions that perform the following tasks:

  • Insert (word): This inserts a word into the trie.

  • Search (word): This searches the given word in the trie and returns TRUE if the complete word is found (i.e., all characters match and the last node is marked as the end of a word). Otherwise, return FALSE.

  • Search prefix (prefix): This searches the given prefix in the trie and returns TRUE if the prefix path exists in the trie (i.e., all prefix characters match), regardless of whether the last node is marked as the end of a word. Otherwise, return FALSE.

Constraints:

  • 11 \leq word.length, prefix.length 500\leq 500

  • The strings consist only of lowercase English letters.

  • At most, 10310^3 calls in total will be made to the functions.