Last active
January 26, 2024 17:58
-
-
Save yevmoroz/8d469b44eb58994b1f6b7dcad7796466 to your computer and use it in GitHub Desktop.
leetcode trie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns an instance of Trie data structure to fill with | |
* strings that can be searched through with high efficiency | |
* Example usage: | |
* ``` | |
* const words = ['cats', 'dogs', 'racoons', 'foxes']; | |
* const t = trie(); | |
* words.forEach(t.insert); | |
* t.search('cat'); // false | |
* t.search('cat', true); // true | |
* t.search('cats'); // true | |
* ``` | |
*/ | |
const trie = () => { | |
const node = (value) => ({ | |
value, | |
isEndOfWord: false, | |
children: {} | |
}); | |
const root = node(null); | |
const insert = (word) => { | |
let current = root; | |
for (let char of word){ | |
if (current.children[char] === undefined) { | |
current.children[char] = node(char); | |
} | |
current = current.children[char]; | |
} | |
current.isEndOfWord = true; | |
} | |
const search = (word, startsWith = false) => { | |
let current = root; | |
for (let char of word) { | |
if (current.children[char] === undefined) { | |
return false; | |
} | |
current = current.children[char]; | |
} | |
return startsWith || current.isEndOfWord; | |
} | |
return { | |
insert, | |
search, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment