How to convert a list of strings and group all the anagrams into sublists in Kotlin

1 Answer

0 votes
fun groupAnagrams(words: List<String>): List<List<String>> {
    // Validate input
    require(words.all { it.isNotEmpty() }) { "All elements must be non-empty strings." }

    // Group words by their sorted character key
    val map = mutableMapOf<String, MutableList<String>>()

    for (word in words) {
        val key = word.toCharArray().sorted().joinToString("")
        map.getOrPut(key) { mutableListOf() }.add(word)
    }

    // Return grouped anagrams as a list of lists
    return map.values.toList()
}

fun main() {
    val lst = listOf("eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro")

    try {
        val result = groupAnagrams(lst)
        println("Grouped anagrams:")
        result.forEach { group ->
            println(group)
        }
    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}



/*
run:

Grouped anagrams:
[eat, tea, ate]
[rop, orp, pro]
[nat, tan]
[bat]

*/

 



answered Nov 15, 2025 by avibootz
...