|
| 1 | +// Space complexity: O(n * m), where n is the number of words and m is the average length of the words stored in the trie. |
| 2 | +var Trie = function () { |
| 3 | + this.root = {}; // Initialize the trie with a root node |
| 4 | +}; |
| 5 | + |
| 6 | +/** |
| 7 | + * @param {string} word |
| 8 | + * @return {void} |
| 9 | + */ |
| 10 | + |
| 11 | +// Time Complexity: O(m), where m is the length of the word being inserted |
| 12 | +Trie.prototype.insert = function (word) { |
| 13 | + let currentNode = this.root; |
| 14 | + for (any of word) { |
| 15 | + // If the character doesn't exist, create a new node |
| 16 | + if (!currentNode[any]) { |
| 17 | + currentNode[any] = {}; |
| 18 | + } |
| 19 | + currentNode = currentNode[any]; // Move to the next node |
| 20 | + } |
| 21 | + currentNode.end = true; // Mark the end of the word |
| 22 | +}; |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {string} word |
| 26 | + * @return {boolean} |
| 27 | + */ |
| 28 | +// Time Complexity: O(m), where m is the length of the word being searched |
| 29 | +Trie.prototype.search = function (word) { |
| 30 | + let currentNode = this.root; |
| 31 | + for (any of word) { |
| 32 | + // If the character doesn't exist in the trie, return false |
| 33 | + if (!currentNode[any]) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + currentNode = currentNode[any]; // Move to the next node |
| 37 | + } |
| 38 | + |
| 39 | + return currentNode.end === true; |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * @param {string} prefix |
| 44 | + * @return {boolean} |
| 45 | + */ |
| 46 | +// Time Complexity: O(m), where m is the length of the prefix |
| 47 | +Trie.prototype.startsWith = function (prefix) { |
| 48 | + let currentNode = this.root; |
| 49 | + |
| 50 | + for (any of prefix) { |
| 51 | + // If the character doesn't exist, return false |
| 52 | + if (!currentNode[any]) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + currentNode = currentNode[any]; // Move to the next node |
| 56 | + } |
| 57 | + |
| 58 | + return true; // Return true if the prefix exists |
| 59 | +}; |
| 60 | + |
| 61 | +/** |
| 62 | + * Your Trie object will be instantiated and called as such: |
| 63 | + * var obj = new Trie() |
| 64 | + * obj.insert(word) |
| 65 | + * var param_2 = obj.search(word) |
| 66 | + * var param_3 = obj.startsWith(prefix) |
| 67 | + */ |
| 68 | + |
| 69 | + |
0 commit comments