# [Group Anagrams](https://leetcode.com/problems/group-anagrams/) ###### tags: `Leetcode`, `Medium`, `Arrays and Hashing` ## Approach * Since all the words in the input list are comprised of lower case english letters, there is a fixed number of such letters i.e 26 * Initialize a HashMap where the keys are tuples comprised of 26 binary elements with that index position of the word set to 1 in the tuple. **Example:** ``` if word = "abc" key = [1, 1, 1, 0, 0, 0, 0, 0, 0, .....] value = [["abc", "cba"]] ``` * Return the values of the hashmap ## Asymptotic Analysis N = length of the input list `strs` K = maximum length of a string in input list `strs` ### Time Complexity: **O(N.K)** ### Space Complexity: **O(N.K)** ## Code ``` python from collections import defaultdict from typing import List class GroupAnagrams: @staticmethod def group_anagrams(strs_list: List[str]) -> List[List[str]]: result_hash = defaultdict(list) for word in strs_list: current_key = [0] * 26 for char in word: current_key[ord(char) - ord('a')] += 1 result_hash[tuple(current_key)].append(word) return result_hash.values() strs = ["eat", "tea", "tan", "ate", "nat", "bat"] print(GroupAnagrams.group_anagrams(strs)) ```