✅☑Beats 100% Users || Easy Understood Solution with optimized space || 3 Approaches🔥
\n\n\n\n# Explanation 1\n  - Objective: \n    - The groupAnagrams method is designed to group a list of words into anagrams.\n  - Data Structure: \n    - It uti
![1.PNG](https://assets.leetcode.com/users/images/9d6a4cc8-5e09-4ce5-a4c4-2de7bfb5cd24_1707194315.8256855.png)\n\n\n\n# Explanation 1\n  - Objective: \n    - The groupAnagrams method is designed to group a list of words into anagrams.\n  - Data Structure: \n    - It utilizes a dictionary (d) to store anagram groups. The key for each group is the sorted version of the words.\n  - Processing:\n    - It iterates through each word in the input list (words).\n    - For each word, it creates a key (s) by sorting its characters using "".join(sorted(i)).\n    - Checks if the key is already present in the dictionary (d).\n    - If not present, it adds a new entry with the key and a list containing the word.\n    - If already present, it appends the word to the existing list associated with that key.\n  - Return Value: \n    - The method returns the values (anagram groups) of the dictionary (d.values()).\n\n# Complexity\n- Time complexity: O(N * K * log(K)), where N is the number of words, and K is the maximum length of a word.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N * K)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# brute-force solution\n  - Note: \n    - This brute-force approach has a higher time complexity and may not be as efficient as using a dictionary for faster lookups, as shown in the earlier optimized solutions.\n```\nclass Solution:\n    def areAnagrams(self, word1: str, word2: str) -> bool:\n        # Function to check if two words are anagrams\n        return sorted(word1) == sorted(word2)\n\n    def groupAnagrams(self, words: List[str]) -> List[List[str]]:\n        # List to store groups of anagrams\n        anagram_groups = []\n\n        # Iterate through each word in the input list\n        for word in words:\n            # Check if the word is already assigned to an existing group\n            assigned = False\n            for group in anagram_groups:\n                if self.areAnagrams(word, group[0]):\n                    group.append(word)\n                    assigned = True\n                    break\n            \n            # If the word is not assigned, create a new group\n            if not assigned:\n                anagram_groups.append([word])\n\n        return anagram_groups\n```\n# code 1\n``` Python []\nclass Solution:\n    def groupAnagrams(self, words: List[str]) -> List[List[str]]:\n        # Dictionary to store anagram groups\n        anagram_groups = {}\n        \n        # Iterate through each word in the input list\n        for word in words:\n            # Sort the characters in the word to create a key\n            key = "".join(sorted(word))\n            \n            # If key is not in the dictionary, add a new entry with the word as a list\n            if key not in anagram_groups:\n                anagram_groups[key] = [word]\n            # If key is already present, append the word to the existing list\n            else:\n                anagram_groups[key].append(word)\n        \n        # Return the values (anagram groups) of the dictionary\n        return anagram_groups.values()\n\n```\n``` C++ []\n#include <vector>\n#include <unordered_map>\n#include <algorithm>\n\nclass Solution {\npublic:\n    vector<vector<string>> groupAnagrams(vector<string>& words) {\n        // Unordered map to store anagram groups\n        unordered_map<string, vector<string>> anagramGroups;\n        \n        // Iterate through each word in the input vector\n        for (const string& word : words) {\n            // Sort the characters in the word to create a key\n            string key = word;\n            sort(key.begin(), key.end());\n            \n            // If key is not in the map, add a new entry with the word as a vector\n            if (anagramGroups.find(key) == anagramGroups.end()) {\n                anagramGroups[key] = {word};\n            }\n            // If key is already present, append the word to the existing vector\n            else {\n                anagramGroups[key].push_back(word);\n            }\n        }\n        \n        // Convert map values to a vector and return\n        vector<vector<string>> result;\n        for (const auto& group : anagramGroups) {\n            result.push_back(group.second);\n        }\n        \n        return result;\n    }\n};\n```\n``` Java []\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nclass Solution {\n    public List<List<String>> groupAnagrams(String[] words) {\n        // Map to store anagram groups\n        Map<String, List<String>> anagramGroups = new HashMap<>();\n        \n        // Iterate through each word in the input array\n        for (String word : words) {\n            // Sort the characters in the word to create a key\n            char[] charArray = word.toCharArray();\n            Arrays.sort(charArray);\n            String key = new String(charArray);\n            \n            // If key is not in the map, add a new entry with the word as a list\n            if (!anagramGroups.containsKey(key)) {\n                anagramGroups.put(key, new ArrayList<>(List.of(word)));\n            }\n            // If key is already present, append the word to the existing list\n            else {\n                anagramGroups.get(key).add(word);\n            }\n        }\n        \n        // Convert map values to a list and return\n        return new ArrayList<>(anagramGroups.values());\n    }\n}\n\n```\n``` JavaScript []\nclass Solution {\n    func groupAnagrams(_ words: [String]) -> [[String]] {\n        // Dictionary to store anagram groups\n        var anagramGroups = [String: [String]]()\n\n        // Iterate through each word in the input array\n        for word in words {\n            // Sort the characters in the word to create a key\n            let key = String(word.sorted())\n\n            // If key is not in the dictionary, add a new entry with the word as an array\n            if anagramGroups[key] == nil {\n                anagramGroups[key] = [word]\n            }\n            // If key is already present, append the word to the existing array\n            else {\n                anagramGroups[key]?.append(word)\n            }\n        }\n\n        // Convert dictionary values to an array and return\n        return Array(anagramGroups.values)\n    }\n}\n\n```\n# Explanation 2\n  - Objective: \n    - Write anagrams from JSON arrays in standard input to a \'user.out\' file in a specific format.\n  - File Handling:\n    - It opens a file named \'user.out\' in write mode.\n  - Input Processing:\n    - It uses map(loads, stdin) to read lines from the standard input, where loads deserializes each line as a JSON array of strings.\n    - For each line, it processes the strings to identify anagrams and groups them based on sorted characters using a defaultdict (w).\n  - Anagram Grouping:\n    - It creates a defaultdict (w) to store anagram groups, where the key is the sorted version of each string.\n    - It iterates through each string in the input, sorts its characters, and appends the original string to the corresponding anagram group.\n  - Output Formatting:\n    - It prints the values of the defaultdict (w.values()) in a string format.\n    - The string is manipulated to replace single quotes with double quotes, remove spaces, and extract the actual content between the brackets [12:-1].\n    - The resulting string is then written to the \'user.out\' file.\n  - Exit:\n    - The exit() statement terminates the program.\n# Note:\n  - The usage of stdin is assumed but not defined in the provided snippet.\n\n# Code 2 \uD83D\uDD25\n```\n# Open a file named \'user.out\' in write mode\nf = open(\'user.out\', \'w\')\n\n# Loop through each line of input using the map function and loads to deserialize JSON\nfor strs in map(loads, stdin):\n    \n    # Create a defaultdict to store anagrams based on sorted characters\n    w = defaultdict(list)\n    \n    # Iterate through each string in the input\n    for s in strs:\n        # Sort the characters in the string and use the sorted version as a key\n        w[\'\'.join(sorted(s))].append(s)\n\n    # Print the values of the defaultdict to the file, converting to JSON-like format\n    print(str(w.values())[12:-1].replace("\'", \'"\').replace(" ", ""), file=f)\n\n# Exit the program\nexit()\n```\n![leetcode up1.png](https://assets.leetcode.com/users/images/a360bb2c-6138-4b8a-b82d-244efb55d72a_1707185294.7299802.jpeg)\n
['Hash Table', 'String', 'Ordered Map', 'Sorting', 'Hash Function', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']