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]
*/