49. Group Anagrams

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.

:

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());
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.