Skip to content

Instantly share code, notes, and snippets.

@uztbt
Created June 21, 2021 02:17
Show Gist options
  • Save uztbt/21c152c12f31baf4fdca44a56df50f67 to your computer and use it in GitHub Desktop.
Save uztbt/21c152c12f31baf4fdca44a56df50f67 to your computer and use it in GitHub Desktop.
class TNode {
letter: string;
num: number;
children: { [letter: string]: TNode };
constructor(letter: string) {
this.letter = letter;
this.num = 1;
this.children = {};
}
}
class Trie {
root: TNode;
constructor() {
this.root = new TNode("");
}
add(name: string) {
let current = this.root;
current.num += 1;
for (let i = 0; i < name.length; i++) {
const char = name[i];
if (typeof current.children[char] === "undefined") {
current.children[char] = new TNode(char);
current = current.children[char];
} else {
current = current.children[char];
current.num += 1;
}
}
}
find(name: string): number {
let current = this.root;
for (let i = 0; i < name.length; i++) {
const char = name[i];
if (typeof current.children[char] === "undefined") {
return 0;
} else {
current = current.children[char];
}
}
return current.num;
}
}
function contacts(queries: string[][]): number[] {
// Write your code here
// - Add the responses to `ans` array
// Make a trie
// - class TNode
// Add name
// Iterate over each char of `name`
// current = root
// current.num += 1
// for char of name:
// if current.children[char] is undefined:
// # Create a new node!
// current.children[char] = new TNode(char);
// current = current.children[char]
// else:
// current = current.children[char]
// current.num += 1
const trie = new Trie();
const ans: number[] = [];
for (const query of queries) {
switch (query[0]) {
case "add":
trie.add(query[1]);
break;
case "find":
const num = trie.find(query[1]);
ans.push(num);
break;
}
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment