/** * This tries to solve the problem by building a trie of all the usernames. It uses recursion, so it might fail on the * stack size but should be fine with a max depth of 1000 chars. */ fun main() { val stringTrie = StringTrie() val words = System.`in`.bufferedReader().lineSequence().drop(1).toList() println(stringTrie.calculateMinStore(words)) } class StringTrie { private var edges = mutableMapOf>() fun insert(string: CharSequence) { edges.putIfAbsent(string.first(), mutableListOf()) edges.getValue(string.first()).add(string.drop(1)) } fun calculateMinStore(words: List, depth: Long = 1L): Long { val trie = StringTrie() words.forEach { trie.insert(it) } return trie.edges.values.sumOf { when (it.size) { 1 -> depth else -> calculateMinStore(it, depth + 1) } } } }