LeetCode 49: Group Anagrams

Problem Description

Explanation:

To group anagrams together, we can use a hashmap where the key is a sorted version of each word, and the value is a list of anagrams that match the sorted key. We iterate through each word in the input array, sort it, and then add it to the corresponding list in the hashmap. Finally, we return the values of the hashmap as the grouped anagrams.

  • Algorithm:

    1. Initialize a hashmap to store the grouped anagrams.
    2. Iterate through each word in the input array.
    3. Sort the characters of the word and use it as a key in the hashmap.
    4. If the key is not present in the hashmap, add it with a new list.
    5. Add the word to the list corresponding to the key.
    6. Return the values of the hashmap as the grouped anagrams.
  • Time Complexity: O(n * k * log k) where n is the number of words and k is the maximum length of a word.

  • Space Complexity: O(n * k) for the hashmap.

:

Solutions

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] charArray = str.toCharArray();
            Arrays.sort(charArray);
            String sortedStr = new String(charArray);
            if (!map.containsKey(sortedStr)) {
                map.put(sortedStr, new ArrayList<>());
            }
            map.get(sortedStr).add(str);
        }
        return new ArrayList<>(map.values());
    }
}

Loading editor...