Implement Trie Prefix Tree - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

A Trie stores strings character by character along root→leaf paths. Each node holds a map of children (next characters) and a boolean flag endOfTheWord that marks the completion of a valid word. During insertion, if a child for a character already exists, it is reused instead of recreated — ensuring that common prefixes are shared and traversal simply follows existing paths from the root.

🔧 Operations

  • insert(word): Walk from the root over the characters of word. If a child for the current character doesn’t exist, create it. After the last character, set endOfTheWord = true.
  • search(word): Traverse the path for all characters of word. If at any step a child is missing, return false. Otherwise, return true only if the final node has endOfTheWord = true.
  • startsWith(prefix): Traverse the path for all characters of prefix. If any child is missing, return false; if the full path exists, return true (no need for endOfTheWord).

🧠 Correctness Intuition

Because all words sharing a prefix converge to the same node reached by that prefix, verifying a prefix is just checking the existence of a path from the root. Verifying a whole word additionally requires the terminal node to be marked with endOfTheWord.

⏱️ Complexity

Let L be the length of the input string (word or prefix).
Time: O(L) for insert, search, and startsWith (one step per character).
Space: Up to O(totalCharacters) across all inserted words (each distinct edge/node created at most once).

Time Complexity

Let L be the length of the input string (word or prefix).
Each operation — insert, search, and startsWith — runs in O(L) time, since at most one node is visited (and in some cases created as well) per character.

Space Complexity

Let L be the input word length, and M be the total number of characters across all inserted words.

  • Per insert (single word of length L): O(L). At most L new nodes are created — the worst case occurs when no existing prefix is already available in the Trie. The endOfTheWord flag adds O(1), which does not affect the overall complexity.
  • Building the whole Trie (all words): O(M). At most M nodes are created — the worst case occurs when no shared prefixes exist.

Visucodize editorial solution titled JS Solution for LeetCode's Implement Trie Prefix Tree coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/implement-trie-prefix-tree.