Implementing Trie in TypeScript

TheTechnoCult
1 min readNov 5, 2023

--

Complexity is a constant time O(1)

class TrieNode {
children: Map<string, TrieNode>
isWord: boolean

constructor() {
this.children = new Map<string, TrieNode>()
this.isWord = false
}
}

class Trie {
public root: TrieNode

constructor() {
this.root = new TrieNode()
}

insert(word: string): void {
let node = this.root
for (let char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode())
}
node = node.children.get(char)
}
node.isWord = true
}

private traverse(word: string): TrieNode | undefined {
let node = this.root
for (let char of word) {
if (!node.children.has(char)) {
return undefined
}
node = node.children.get(char)
}
return node
}

search(word: string): boolean {
const node = this.traverse(word)
return Boolean(node?.isWord)
}

startsWith(prefix: string): boolean {
const node = this.traverse(prefix)
return Boolean(node)
}
}

or just

class Trie {
set: Set<string>

constructor() {
this.set = new Set()
}

insert(word: string): void {
this.set.add(word)
}

search(word: string): boolean {
return this.set.has(word)
}

startsWith(prefix: string): boolean {
for (let c of this.set) {
if (c.indexOf(prefix) === 0) {
return true
}
}
return false
}
}

--

--

No responses yet