Skip to content

Instantly share code, notes, and snippets.

@Husseinhj
Created August 8, 2022 17:02
Show Gist options
  • Save Husseinhj/0ec6f464eb56e955993e2a778872cabd to your computer and use it in GitHub Desktop.
Save Husseinhj/0ec6f464eb56e955993e2a778872cabd to your computer and use it in GitHub Desktop.
Group Anagrams
package org.kotlinlang.play
fun main() {
val sample = listOf("eat","tea","tan","ate","nat","bat")
println(anagrams(sample))
}
fun anagrams(words: List<String>): List<List<String>> {
val hashMap = hashMapOf<String, List<String>>()
words.forEach { word ->
val newWord = word.toCharArray().sortedArray().concatToString()
if (hashMap.containsKey(newWord)) {
val list = hashMap[newWord] ?: listOf()
val muList = list.toMutableList()
muList.add(word)
hashMap[newWord] = muList
} else {
hashMap[newWord] = listOf(word)
}
}
return hashMap.keys.map {
hashMap[it]!!
}
}
@Husseinhj
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment