No Prefix Set

  • + 0 comments

    Kotlin Building Trie and checking on a fly

    fun noPrefix(words: Array<String>): Unit {
        // Write your code here
        val tree = Node("")
        for (word in words) {
            var key = tree.text
            var parentNode = tree
            for (char in word) {
                key += char
                val node = parentNode.children.find { it.text == key } ?: Node(key)
                    .also(parentNode.children::add)
                if (node.isWord) {
                    println("BAD SET")
                    println(word)
                    return
                }
                parentNode = node
            }
            if (parentNode.children.isNotEmpty()) {
                println("BAD SET")
                println(word)
                return
            }
            parentNode.isWord = true
        }
        println("GOOD SET")
    }
    
    data class Node(
        var text: String,
        var isWord: Boolean = false,
        var children: MutableCollection<Node> = mutableListOf(),
    ) {
    }