Group Anagrams
1 min read

Group Anagrams

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"] 
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

Example 2:
Input: strs = [""]
Output: [[""]]

Example 3:
Input: strs = ["a"]
Output: [["a"]]

fun groupAnagrams(strs: Array<String>): List<List<String>> {
    val anagrams = mutableMapOf<String, MutableList<String>>()
    for (s in strs) {
        val key = s.toCharArray().sorted().joinToString("") // create a key by sorting the letters of the string
        if (key in anagrams) {
        } else {
            anagrams[key] = mutableListOf(s)
    return anagrams.values.toList()

This solution uses a map to keep track of the anagrams, where the key is a string formed by sorting the letters of the original string, and the value is a list of strings that are anagrams of the key. The function iterates through the input list of strings, creates a key for each string by sorting its letters, and adds the string to the corresponding list of anagrams in the map. Finally, it returns the values (lists of anagrams) of the map as a list.

This solution has a time complexity of O(n*k log k) where n is the number of strings and k is the average length of the strings.