Skip to content

Instantly share code, notes, and snippets.

@dragneelfps
Created May 6, 2021 04:40
Show Gist options
  • Save dragneelfps/4556e24df086bc72033ec61f6fdffc0b to your computer and use it in GitHub Desktop.
Save dragneelfps/4556e24df086bc72033ec61f6fdffc0b to your computer and use it in GitHub Desktop.
TRIE data structure in Kotlin
class Trie() {
private data class Node(val children: MutableList<Node?> = MutableList(26) { null }, var leaf: Boolean = false)
private val root = Node()
/** Inserts a word into the trie. */
fun insert(word: String) {
var curr = root
for(ch in word) {
val idx = ch.idx()
if(curr.children[idx] == null) {
curr.children[idx] = Node()
}
curr = curr.children[idx]!!
}
curr.leaf = true
}
/** Returns if the word is in the trie. */
fun search(word: String): Boolean {
var curr = root
for(ch in word) {
val idx = ch.idx()
if(curr.children[idx] == null) {
return false
}
curr = curr.children[idx]!!
}
return curr.leaf
}
/** Returns if there is any word in the trie that starts with the given prefix. */
fun startsWith(prefix: String): Boolean {
var curr = root
for(ch in prefix) {
val idx = ch.idx()
if(curr.children[idx] == null) {
return false
}
curr = curr.children[idx]!!
}
return true
}
private fun Char.idx() = toInt() - 'a'.toInt()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment