MEDIUM NC#61 Blind #71 Tries - Prefix Tree

208. Implement Trie (Prefix Tree)

๐Ÿ“– Problem

Implement a Trie with insert, search, and startsWith methods. - insert(word): Inserts word into trie - search(word): Returns true if word is in trie - startsWith(prefix): Returns true if any word with this prefix exists

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ Trie nodes have children Map and isEndOfWord flag
  • โ†’ insert: traverse/create nodes for each character, mark last as end
  • โ†’ search: traverse nodes, return isEndOfWord at the end
  • โ†’ startsWith: traverse nodes, return true if all characters found
  • โ†’ Time: O(L) per operation where L = word/prefix length
  • โ†’ Space: O(total characters inserted)

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขTrie nodes have children Map and isEndOfWord flag
  • โ€ขinsert: traverse/create nodes for each character, mark last as end
  • โ€ขsearch: traverse nodes, return isEndOfWord at the end

Common Pitfalls

  • โ€ขstartsWith: traverse nodes, return true if all characters found
  • โ€ขTime: O(L) per operation where L = word/prefix length
  • โ€ขSpace: O(total characters inserted)

๐Ÿงช Test Cases

Hidden tests on submit: 3

Test Case 1
Not run
Input:
(() => { const trie = new Trie(); return trie.insert('apple'); })();
Expected:
null
Test Case 2
Not run
Input:
(() => { const trie = new Trie(); trie.insert('apple'); return trie.search('apple'); })();
Expected:
true
Test Case 3
Not run
Input:
(() => { const trie = new Trie(); trie.insert('apple'); trie.search('apple'); return trie.search('app'); })();
Expected:
false

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit