Explorer
Node.js

Implement a Trie (prefix tree) with `insert(word)`, `search(word)`, and `startsWith(prefix)` methods.

Problem Statement

Implement a Trie (prefix tree) with `insert(word)`, `search(word)`, and `startsWith(prefix)` methods.

Complexity

Time Complexity: -

Space Complexity: -

Hints

šŸ’” Hint 1: A Trie stores characters in tree nodes. Each path from root = a prefix. šŸ’” Hint 2: Each node has children (a Map/object) and an isEnd flag. šŸ’” Hint 3: Insert: walk through chars, create nodes. Search: walk and check isEnd. startsWith: walk and check existence. āœ… Solution: ```javascript class Trie { constructor() { this.root = {}; } insert(word) { let node = this.root; for (const c of word) { if (!node[c]) node[c] = {}; node = node[c]; } node.isEnd = true; } search(word) { let node = this.root; for (const c of word) { if (!node[c]) return false; node = node[c]; } return node.isEnd === true; } startsWith(prefix) { let node = this.root; for (const c of prefix) { if (!node[c]) return false; node = node[c]; } return true; } } ```

Trie Data Structure

Hard
Implement a Trie (prefix tree) with `insert(word)`, `search(word)`, and `startsWith(prefix)` methods.
Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"search_apple":true,"search_app":true,"search_ap":false,"starts_ap":true}