Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

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
...