Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Last active February 6, 2017 20:45
Show Gist options
  • Save jasonwaters/f7b8eb87f6148f05c4e9649cb4968754 to your computer and use it in GitHub Desktop.
Save jasonwaters/f7b8eb87f6148f05c4e9649cb4968754 to your computer and use it in GitHub Desktop.
Tries: Contacts
// https://www.hackerrank.com/challenges/ctci-contacts
function Trie() {
this.data = {};
}
Trie.prototype.process = function(op, str) {
if(op === 'add') {
let data = this.data;
for(let char of str) {
if(!data[char]) {
data[char] = {count: 0}
}
data[char].count++;
data = data[char];
}
}else if(op === 'find') {
let data = this.data;
for(let char of str) {
if(typeof data[char] != 'undefined') {
data = data[char];
}else {
console.log(0);
return;
}
}
console.log(data.count);
}
}
Trie.prototype.dump = function() {
console.log(this.data);
}
////////////////////
let input = `4
add hack
add hackerrank
find hac
find hak`;
let commands = input.split('\n').slice(1).map(line => line.split(' '));
let t = new Trie();
commands.forEach(command => t.process(command[0], command[1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment