Leetcode: Group Anagrams (Kotlin)
Kotlin

Leetcode: Group Anagrams (Kotlin)

December 29, 2024

Leetcode: Group Anagrams (Kotlin)

This problem is a medium string and array problem on Leetcode. I will walk through an approach to solving this problem. Group Anagrams - LeetCode

Problem Statement

Examples

Constraints

Understanding the Problem

First, you should understand what an anagram is. An anagram is a word you can form by rearranging the letters of another word. They give you a list of words and want you to return a list of lists. The inner list will be the group of lists.

Brainstorm

My first approach was to use a map to keep a count of each character for each word. I was thinking about using a map of maps or a list of maps. Thinking about how to structure this brought me to my second approach.

Sort each word and use that as a key in the map. Have a list of indexes or a list of each word.

I decided to go with the list of words since the list of indexes required a little more work on grouping and adding the words to the group list.

Also, since I could return the list of groups in any order, I could just turn the map into a list and return that.

Instead of the split function, we could have also used toCharArray(). We must turn the string into a character array to sort them. We can then use joinToString() to turn the array back into a string. We could have done this by passing the char array to the String constructor.

Solution

class Solution {
    fun groupAnagrams(strs: Array<String>): List<List<String>> {
        
        val map = mutableMapOf<String, MutableList<String>>()
        
        for(word in strs){
            val sortedWord = word.split("").sorted().joinToString("")
            if(!map.containsKey(sortedWord)) map[sortedWord] = mutableListOf()
            map[sortedWord]?.add(word)
        }
        
        return map.values.toList()
    }
}