Skip to content

Commit 401764d

Browse files
committed
Add and search word
1 parent 713b1b6 commit 401764d

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* Class representing a Trie data structure.
3+
* @summary Add and Search Word - Data structure design {@link https://leetcode.com/problems/add-and-search-word-data-structure-design/}
4+
* @description Implement a structure that allows to add words and search words with wildcard support.
5+
*/
6+
class WordDictionary {
7+
/**
8+
* @description Create a new Trie with root node.
9+
*/
10+
constructor() {
11+
this.trie = {};
12+
}
13+
14+
/**
15+
* @description Add word to the trie (supported letters a-z).
16+
* @param {string} word String to be added to our trie.
17+
* Space O(n) - where n is word.length - at best we add 0 chars (word is already here), at worst word.length - when none of the leaves/branches exist.
18+
* Time O(n) - where n is word.length, iterate over string length.
19+
*/
20+
addWord(word) {
21+
let currentNode = this.trie;
22+
23+
for (let index = 0; index < word.length; index++) {
24+
const char = word[index];
25+
26+
if (!currentNode[char]) currentNode[char] = {};
27+
28+
currentNode = currentNode[char];
29+
}
30+
31+
currentNode.hasWord = true;
32+
}
33+
34+
/**
35+
* @description Search word in a trie (supported letters a-z and match all char '.').
36+
* @param {string} word String to search for
37+
* @param {Object} [node=this.trie] Node currently at, defaults to trie root.
38+
* @param {number} index Position of current node relative to search term.
39+
* @return {boolean} true mmatching value found in trie.
40+
* Space(n) - for stack (recursion).
41+
* Time O(m*n) - for worst case scenario (all '.') we have to traverse all leaves(m) to word.length(n) depth.
42+
*/
43+
search(word, node = this.trie, index = 0) {
44+
const SPECIAL_CHAR = '.';
45+
46+
const char = word[index];
47+
48+
if (index === word.length - 1) {
49+
if (char === SPECIAL_CHAR) return Object.keys(node).some(key => node[key].hasWord);
50+
return !!node[char]?.hasWord;
51+
}
52+
53+
if (char === SPECIAL_CHAR) return Object.keys(node).some(key => this.search(word, node[key], index + 1));
54+
if (char !== SPECIAL_CHAR) {
55+
if (!node[char]) return false;
56+
else return this.search(word, node[char], index + 1);
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)