|
| 1 | +class Node { |
| 2 | + constructor() { |
| 3 | + this.links = new Array(26); |
| 4 | + this.flag = false; |
| 5 | + } |
| 6 | + |
| 7 | + // Check whether the node contains the specific key (character) |
| 8 | + containsKey(character) { |
| 9 | + return ( |
| 10 | + this.links[character.charCodeAt(0) - "a".charCodeAt(0)] !== undefined |
| 11 | + ); |
| 12 | + } |
| 13 | + |
| 14 | + // Insert a new node with the specific key (character) |
| 15 | + insert(character, node) { |
| 16 | + return (this.links[character.charCodeAt(0) - "a".charCodeAt(0)] = node); |
| 17 | + } |
| 18 | + |
| 19 | + // Fetch the node with the specific key (character) |
| 20 | + get(character) { |
| 21 | + return this.links[character.charCodeAt(0) - "a".charCodeAt(0)]; |
| 22 | + } |
| 23 | + |
| 24 | + // Set the node as end of the word |
| 25 | + setEnd() { |
| 26 | + this.flag = true; |
| 27 | + } |
| 28 | + |
| 29 | + // Get the flag of the node that helps to identify it's end of word or not |
| 30 | + getEnd() { |
| 31 | + return this.flag; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +export class Trie { |
| 36 | + constructor() { |
| 37 | + this.root = new Node(); |
| 38 | + } |
| 39 | + |
| 40 | + // O(k) where k is length of string |
| 41 | + insert(word) { |
| 42 | + let node = this.root; |
| 43 | + |
| 44 | + for (let index = 0; index < word.length; index++) { |
| 45 | + const character = word[index]; |
| 46 | + |
| 47 | + // character is not present in the trie |
| 48 | + if (!node.containsKey(character)) { |
| 49 | + node.insert(character, new Node()); |
| 50 | + } |
| 51 | + |
| 52 | + // As character is present, move to next node |
| 53 | + node = node.get(character); |
| 54 | + } |
| 55 | + |
| 56 | + // Mark the end of the word |
| 57 | + node.setEnd(); |
| 58 | + } |
| 59 | + |
| 60 | + // O(k) where k is length of string |
| 61 | + startsWith(word) { |
| 62 | + let traverse = this.root; |
| 63 | + |
| 64 | + for (let index = 0; index < word.length; index++) { |
| 65 | + const element = word[index]; |
| 66 | + |
| 67 | + if (!traverse.containsKey(element)) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + |
| 71 | + traverse = traverse.get(element); |
| 72 | + } |
| 73 | + |
| 74 | + return true; |
| 75 | + } |
| 76 | + |
| 77 | + // O(k) where k is length of string |
| 78 | + search(word) { |
| 79 | + let traverse = this.root; |
| 80 | + |
| 81 | + for (let index = 0; index < word.length; index++) { |
| 82 | + const element = word[index]; |
| 83 | + |
| 84 | + if (!traverse.containsKey(element)) { |
| 85 | + return false; |
| 86 | + } |
| 87 | + |
| 88 | + traverse = traverse.get(element); |
| 89 | + } |
| 90 | + |
| 91 | + return traverse.getEnd(); |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +function main() { |
| 96 | + const trie = new Trie(); |
| 97 | + trie.insert("apple"); |
| 98 | + trie.insert("boy"); |
| 99 | + trie.insert("apply"); |
| 100 | + |
| 101 | +} |
| 102 | + |
| 103 | +main(); |
0 commit comments