✅☑Beats 99% Users || [C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n---\n\n# Approaches\n(Also explained in the code)\n\n#### Approach 1\n\n1. The function getSignature creates a unique sig
# PLEASE UPVOTE IF IT HELPED\n\n---\n![Screenshot 2024-01-25 053401.png](https://assets.leetcode.com/users/images/43541d2c-90a0-4d47-89c4-5badf7eba1c9_1707178477.3126607.png)\n\n---\n\n# Approaches\n(Also explained in the code)\n\n#### ***Approach 1***\n\n1. The function `getSignature` creates a unique signature for each string by counting the occurrences of each character. This signature helps identify anagrams as they have the same character frequencies.\n\n1. The `groupAnagrams` function uses an unordered map (`groups`) to group strings with the same signature (anagrams) together. It iterates through each string, calculates its signature, and adds the string to the corresponding group in the map.\n\n1. The `result` vector stores the final grouped anagrams. It is initially empty and gets populated by iterating through the groups map. Each entry in the map corresponds to a unique signature, and the associated vector contains strings that are anagrams.\n\n\n\n# Complexity\n- Time complexity:\n   $$O(n*k)$$\n*(K is the length of the longest string)*\n    \n\n- Space complexity:\n   $$O(n*k)$$\n*(K is the length of the longest string)*\n    \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n    string getSignature(const string& s) {\n        vector<int> count(26, 0);\n        for (char c : s) {\n            count[c - \'a\']++;\n        }\n\n        stringstream ss;\n        for (int i = 0; i < 26; i++) {\n            if (count[i] != 0) {\n                ss << (char)(\'a\' + i) << count[i];\n            }\n        }\n        return ss.str();\n    }\n\n    vector<vector<string>> groupAnagrams(vector<string>& strs) {\n        vector<vector<string>> result;\n        unordered_map<string, vector<string>> groups;\n\n        for (const string& s : strs) {\n            groups[getSignature(s)].push_back(s);\n        }\n\n        for (const auto& entry : groups) {\n            result.push_back(entry.second);\n        }\n\n        return result;\n    }\n};\n\n\n```\n```Java []\n\n\nclass Solution {\n    public String getSignature(String s) {\n        int[] count = new int[26];\n        for (char c : s.toCharArray()) {\n            count[c - \'a\']++;\n        }\n\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < 26; i++) {\n            if (count[i] != 0) {\n                sb.append((char) (\'a\' + i)).append(count[i]);\n            }\n        }\n        return sb.toString();\n    }\n\n    public List<List<String>> groupAnagrams(String[] strs) {\n        List<List<String>> result = new ArrayList<>();\n        Map<String, List<String>> groups = new HashMap<>();\n\n        for (String s : strs) {\n            groups.computeIfAbsent(getSignature(s), k -> new ArrayList<>()).add(s);\n        }\n\n        result.addAll(groups.values());\n\n        return result;\n    }\n}\n\n\n\n```\n```python3 []\nfrom typing import List\nfrom collections import defaultdict\n\nclass Solution:\n    def getSignature(self, s: str) -> str:\n        count = [0] * 26\n        for c in s:\n            count[ord(c) - ord(\'a\')] += 1\n\n        result = []\n        for i in range(26):\n            if count[i] != 0:\n                result.extend([chr(i + ord(\'a\')), str(count[i])])\n\n        return \'\'.join(result)\n\n    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n        result = []\n        groups = defaultdict(list)\n\n        for s in strs:\n            groups[self.getSignature(s)].append(s)\n\n        result.extend(groups.values())\n\n        return result\n\n\n\n```\n```javascript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar getSignature = function(s) {\n    const count = Array(26).fill(0);\n    for (const c of s) {\n        count[c.charCodeAt(0) - \'a\'.charCodeAt(0)]++;\n    }\n\n    const result = [];\n    for (let i = 0; i < 26; i++) {\n        if (count[i] !== 0) {\n            result.push(String.fromCharCode(i + \'a\'.charCodeAt(0)), count[i].toString());\n        }\n    }\n\n    return result.join(\'\');\n};\n\n/**\n * @param {string[]} strs\n * @return {string[][]}\n */\nvar groupAnagrams = function(strs) {\n    const result = [];\n    const groups = new Map();\n\n    for (const s of strs) {\n        const signature = getSignature(s);\n        if (!groups.has(signature)) {\n            groups.set(signature, []);\n        }\n        groups.get(signature).push(s);\n    }\n\n    groups.forEach(value => result.push(value));\n\n    return result;\n};\n\n\n```\n\n---\n\n\n#### ***Approach 2***\n\n1. **Using an Unordered Map:** We utilize an unordered map to store the sorted version of each string (anagram) as the key and the index of the corresponding group in the answer vector as the value. This allows us to quickly check if an anagram group already exists.\n\n1. **Iterating Through the Input Strings:** We iterate through each string in the input vector \'strs\'.\n\n1. **Sorting Strings:** For each string, we sort its characters alphabetically. This ensures that anagrams will have the same sorted representation.\n\n1. **Grouping Anagrams:** We check if the sorted string exists in the unordered map. If it does, we add the current string to the corresponding group in the answer vector. If not, we create a new group and store its index in the unordered map.\n\n1. **Returning the Answer:** Once all strings have been processed, we return the answer vector containing the grouped anagrams.\n\n\n\n# Complexity\n- Time complexity:\n   $$O(n * k * log k)$$\n*(K is the length of the longest string)*\n    \n\n- Space complexity:\n   $$O(n*k)$$\n*(K is the length of the longest string)*\n    \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n    vector<vector<string>> groupAnagrams(vector<string>& strs) {\n        unordered_map<string, int> mp;\n        vector<vector<string>> ans; \n\n        for (int i = 0; i < strs.size(); i++) {\n            string temp = strs[i];\n            sort(temp.begin(), temp.end());\n            if (mp.find(temp) != mp.end()) {\n                ans[mp[temp]].push_back(strs[i]);\n            } else {\n                mp[temp] = ans.size();\n                ans.push_back({strs[i]});\n                \n            }\n        }\n\n        return ans;\n    }\n};\n\n\n\n```\n```Java []\n\n\nclass Solution {\n    public List<List<String>> groupAnagrams(String[] strs) {\n        Map<String, Integer> mp = new HashMap<>();\n        List<List<String>> ans = new ArrayList<>();\n\n        for (String str : strs) {\n            char[] chars = str.toCharArray();\n            Arrays.sort(chars);\n            String sortedStr = new String(chars);\n            \n            if (mp.containsKey(sortedStr)) {\n                ans.get(mp.get(sortedStr)).add(str);\n            } else {\n                mp.put(sortedStr, ans.size());\n                ans.add(new ArrayList<>(Arrays.asList(str)));\n            }\n        }\n\n        return ans;\n    }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n        mp = {}\n        ans = []\n\n        for s in strs:\n            sorted_str = \'\'.join(sorted(s))\n            if sorted_str in mp:\n                ans[mp[sorted_str]].append(s)\n            else:\n                mp[sorted_str] = len(ans)\n                ans.append([s])\n                \n        return ans\n\n\n\n```\n```javascript []\nvar groupAnagrams = function(strs) {\n    const mp = new Map();\n    const ans = [];\n\n    for (const str of strs) {\n        const sortedStr = str.split(\'\').sort().join(\'\');\n        if (mp.has(sortedStr)) {\n            ans[mp.get(sortedStr)].push(str);\n        } else {\n            mp.set(sortedStr, ans.length);\n            ans.push([str]);\n        }\n    }\n\n    return ans;\n};\n\n\n\n\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
['Array', 'Hash Table', 'String', 'Sorting', 'Python', 'C++', 'Java', 'Python3', 'JavaScript']