Skip to content

Commit f692732

Browse files
committed
trie class + dfs O(n) O(n)
1 parent 5e16818 commit f692732

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/**
2+
* @param {string[]} products
3+
* @param {string} searchWord
4+
* @return {string[][]}
5+
*/
6+
7+
// p: arr, str
8+
// r: arr
9+
10+
// m
11+
// |
12+
// o
13+
// / / \
14+
// b n u
15+
// | / \ |
16+
// i e i s
17+
//
18+
// create a class TrieNode
19+
class TrieNode {
20+
constructor() {
21+
this.isWord = false;
22+
this.children = new Array(26).fill(null);
23+
}
24+
}
25+
// a b c d e f g h i j k l m n o p
26+
// children = [x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x]
27+
// create a class Trie
28+
class Trie {
29+
constructor() {
30+
this.root = new TrieNode();
31+
this.alphabet = "abcdefghijklmnopqrstuvwxyz";
32+
}
33+
34+
// insert words from arr to class Trie
35+
insert(word) {
36+
let c = this.root;
37+
let a = this.alphabet;
38+
for (let w of word) {
39+
let i = a.indexOf(w);
40+
!c.children[i] && (c.children[i] = new TrieNode());
41+
c = c.children[i];
42+
}
43+
c.isWord = true;
44+
}
45+
46+
// add words to result array following each prefix
47+
getWordsStartWith(prefix) {
48+
let c = this.root;
49+
let a = this.alphabet;
50+
const result = [];
51+
for (let p of prefix) {
52+
let i = a.indexOf(p);
53+
if (!c.children[i]) return result;
54+
c = c.children[i];
55+
}
56+
57+
this.dfsGetWords(prefix, c, result);
58+
return result;
59+
}
60+
61+
// dfs to get words following prefixes
62+
dfsGetWords(prefix, c, result) {
63+
if (result.length === 3) return;
64+
c.isWord && result.push(prefix);
65+
let a = this.alphabet;
66+
for (let i = 0; i < a.length; i++) {
67+
c.children[i] && this.dfsGetWords(prefix + a[i], c.children[i], result);
68+
}
69+
}
70+
}
71+
72+
var suggestedProducts = function (products, searchWord) {
73+
// create new Trie
74+
const trie = new Trie();
75+
// insert words
76+
for (let p of products) {
77+
trie.insert(p);
78+
}
79+
const result = [];
80+
let prefix = "";
81+
// add words to result array
82+
for (let w of searchWord) {
83+
prefix += w;
84+
result.push(trie.getWordsStartWith(prefix));
85+
}
86+
87+
// return result array
88+
return prefix;
89+
};
90+
91+
const products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"];
92+
const searchWord = "mouse";
93+
console.log(suggestedProducts(products, searchWord));

0 commit comments

Comments
 (0)