Grouping Anagrams Using Sorted Strings as HashMap Keys

---------------🎈🎈 LeetCode Problem 49: Group Anagrams 🎈🎈-------------------

Anagram grouping illustration

In Java, arrays cannot be used directly as keys in a HashMap because their hashCode() method does not reflect the actual content. It is therefore recommended to use immutable objects such as strings as keys.

Approach 1: Use a Sorted String as the Key

⭐️ Since two anagrams contain exactly the same characters, after sorting both strings we get identical results. This sorted string can be used as the key in a HashMap.

  • Convert a string to a character array: char[] chars = str.toCharArray()
  • Convert a character array back to a string: String sorted = new String(chars)
  • Sort an array of characters: Arrays.sort( )
  • Retrieve the collection of all value stored in a HashMap: map.values()
  • Return the grouped anagrams directly: return new ArrayList<>(map.values())

HashMap anagram grouping

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> groupMap = new HashMap<>();

        for (String original : strs) {
            char[] letters = original.toCharArray();
            Arrays.sort(letters);
            String signature = new String(letters);

            // If the sorted key already exists, append the original string to its list
            if (groupMap.containsKey(signature)) {
                List<String> currentList = groupMap.get(signature);
                currentList.add(original);
                groupMap.put(signature, currentList);
            } else {
                // Otherwise create a new list for this key
                List<String> newEntry = new ArrayList<>();
                newEntry.add(original);
                groupMap.put(signature, newEntry);
            }
        }
        return new ArrayList<>(groupMap.values());
    }
}

Approach 2: Simplify Using getOrDefault

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        // In Java, use a String rather than an array as the HashMap key.
        Map<String, List<String>> grouping = new HashMap<>();

        for (String word : strs) {
            char[] charSeq = word.toCharArray();
            Arrays.sort(charSeq);
            String key = new String(charSeq);

            // Retrieve existing list or create a new one with getOrDefault
            List<String> bucket = grouping.getOrDefault(key, new ArrayList<>());
            bucket.add(word);
            grouping.put(key, bucket);
        }
        return new ArrayList<>(grouping.values());
    }
}

Tags: LeetCode hashmap Anagrams java string

Posted on Fri, 18 Sep 2026 16:20:45 +0000 by ckwall