← Back to Leo Academy Masterclass

Problem #49: Group Anagrams

Medium Hashmap

Intuition & Strategy Breakdown

Group strings using a hash map where the key is the sorted character string (or character count array) and the value is a list of anagrams.

Python Solution

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        ans = collections.defaultdict(list)

        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            ans[tuple(count)].append(s)
            
        return ans.values()

Java Solution

class Solution {
    public List> groupAnagrams(String[] strs) {
        Map> ans = new HashMap<>();
        for (String s : strs) {
            int[] count = new int[26];
            for (char c : s.toCharArray()) count[c - 'a']++;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 26; i++) {
                sb.append('#');
                sb.append(count[i]);
            }
            String key = sb.toString();
            if (!ans.containsKey(key)) ans.put(key, new ArrayList<>());
            ans.get(key).add(s);
        }
        return new ArrayList<>(ans.values());
    }
}
Watch Interactive Video on Leo Academy Main App