Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created February 10, 2020 22:28
Show Gist options
  • Save RP-3/743b3e8369a2264edb46a275e367fbf9 to your computer and use it in GitHub Desktop.
Save RP-3/743b3e8369a2264edb46a275e367fbf9 to your computer and use it in GitHub Desktop.
var StreamChecker = function(words) {
this.tree = PrefixTree();
this.maxWordLength = 0;
words.forEach((word) => {
this.tree.add(word.split('').reverse().join(''));
this.maxWordLength = Math.max(this.maxWordLength, word.length);
});
this.storage = []; // should be a queue! This is O(n) time as opposed to a queues O(1)
};
StreamChecker.prototype.query = function(letter) {
if(this.storage.length === this.maxWordLength) this.storage.shift();
this.storage.push(letter);
return this.tree.has(this.storage.length-1, this.storage);
};
const PrefixTree = () => {
const self = {
children: {}, // could use map but this has shorter syntax
terminal: false
};
self.add = (word) => {
if(!word.length){
self.terminal = true;
return;
}
const prefix = word[0];
const suffix = word.slice(1);
if(!self.children.hasOwnProperty(prefix)) self.children[prefix] = PrefixTree();
self.children[prefix].add(suffix);
};
self.has = (index, storage, log=false) => {
if(self.terminal) return true;
if(index < 0) return false;
const prefix = storage[index];
if(!self.children.hasOwnProperty(prefix)) return false;
return self.children[prefix].has(index-1, storage, log);
};
return self;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment