Java || Using a Map || Sorting || Beats 98.95%
Intuition\nThis problem is about grouping words that are anagrams of each other. An anagram is a word formed by rearranging the letters of another word.\n\n\n# 
# Intuition\nThis problem is about grouping words that are anagrams of each other. An anagram is a word formed by rearranging the letters of another word.\n\n\n# Approach\nWe use a HashMap to efficiently group anagrams. The key is the sorted version of a word, and the value is a list of anagrams.\n- We initialize an empty list called `result` to store the grouped anagrams.\n- First, we check if the input `strs` is empty or null. If it is, we return an empty result.\n- If `strs` contains only one word, we wrap it in a list and return it because there are no other words to group.\n- We then go through each word in the `strs` array.\n  - We convert each word into a character array (`charArray`).\n  - We sort the character array, creating the sorted version of the word (`sortedWord`).\n  - If `map` does not contain `sortedWord` as a key, we initialize an empty list for that key.\n  - We add the word to the list corresponding to `sortedWord`.\n- After processing all words, we have grouped the anagrams inside the `map`.\n- We extract the lists of anagrams from the `map` values and add them to the `result` list.\n- Finally, we return the grouped anagrams as the result.\n\n# Complexity\n- Time complexity: O(N * K * log(K))\n  - N represents the number of words in the `strs` array.\n  - K represents the maximum length of a word.\n  - The algorithm iterates through each word (N operations), sorts each word (K * log(K) time complexity), and performs constant-time operations. The dominant factor is the sorting step, resulting in a time complexity of O(N * K * log(K)).\n\n- Space complexity: O(N * K)\n  - The algorithm uses a HashMap to store sorted words as keys and lists of anagrams as values. In the worst case, assuming each word is unique and has a length of K, the space complexity is O(N * K).\n\n\n# Code\n```\nclass Solution {\n  public List<List<String>> groupAnagrams(String[] strs) {\n\n        HashMap<String,List<String>> map=new HashMap<>();\n\n        List<List<String>> result = new ArrayList<>();\n\n\n        for (String word: strs\n        ) {\n            char[] charArray = word.toCharArray();\n\n\n            Arrays.sort(charArray);\n\n            String sortedWord = String.valueOf(charArray);\n\n            if (!map.containsKey(sortedWord)) {\n                map.put(sortedWord, new ArrayList<>());\n            }\n\n\n            map.get(sortedWord).add(word);\n\n\n        }\n        result.addAll(map.values());\n\n        return result;\n    }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp](https://assets.leetcode.com/users/images/4bcbbb97-7806-4680-af9a-63b251d79b5e_1694947233.8470142.webp)\n
['Java']