-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement-trie.ts
More file actions
64 lines (59 loc) · 1.7 KB
/
Copy pathimplement-trie.ts
File metadata and controls
64 lines (59 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* 208. Implement Trie (Prefix Tree) (Medium)
* Link: https://leetcode.com/problems/implement-trie-prefix-tree/
*
* Implement a trie with insert(word), search(word) (exact match), and
* startsWith(prefix).
*
* Example:
* insert("apple");
* search("apple") -> true
* search("app") -> false
* startsWith("app") -> true
* insert("app"); search("app") -> true
*
* Approach:
* A tree of nodes, one edge per character. Each node has a map of children and
* an `isWord` flag. insert walks/creates nodes for each letter; search walks
* and checks isWord at the end; startsWith walks and only needs the path to
* exist. Every operation is proportional to the key length.
*
* Time: O(L) per operation, L = word/prefix length.
* Space: O(total characters inserted).
*/
class TrieNode {
readonly children = new Map<string, TrieNode>();
isWord = false;
}
export class Trie {
private readonly root = new TrieNode();
insert(word: string): void {
let node = this.root;
for (const ch of word) {
let next = node.children.get(ch);
if (!next) {
next = new TrieNode();
node.children.set(ch, next);
}
node = next;
}
node.isWord = true;
}
search(word: string): boolean {
const node = this.walk(word);
return node !== null && node.isWord;
}
startsWith(prefix: string): boolean {
return this.walk(prefix) !== null;
}
/** Follow the path for `key`; return the terminal node or null if it breaks. */
private walk(key: string): TrieNode | null {
let node = this.root;
for (const ch of key) {
const next = node.children.get(ch);
if (!next) return null;
node = next;
}
return node;
}
}