[LeetCode] 49. Group Anagrams

Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Note: All inputs will be in lower-case.

Thought process:
Hash map. If two words have the same letter counts, they can be grouped together. Since all inputs are in lower-case, my first thought is to use and int[26] as the map's key, and a list of strings as the value. However, java does not have a hash function for integer array. So instead, I'll use a char array and store it as a string.

Solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] count = new char[26];
            Arrays.fill(count, '0');
            
            for (char c : str.toCharArray()) {
                count[c - 'a']++;
            }
            String key = new String(count);
            
            if (!map.containsKey(key)) {
                map.put(key, new ArrayList<>());
            }
            map.get(key).add(str);
        }
        
        List<List<String>> groups = new ArrayList<>();
        for (String key : map.keySet()) {
            groups.add(map.get(key));
        }
        return groups;
    }
}

Time complexity:
Say the average length of the strings is l. The overall time complexity is O(ln).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula