LeetCode Problem 49: Group Anagrams

Nisha
1 min readDec 9, 2019

--

Given an array of strings, group anagrams together.

Example:

Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Solution: This problem can be solved in 4 steps.

Step 1: Create a result map of type<String, List>.

Step 2: Iterate over each string in input, convert it to an array, sort it and then convert it back to String.

Step 3: Now check if result.containsKey(key) in result map then result.get(key).add(input str) else, result.put(key, new ArrayList()).

Step 4: return new ArrayList(result.values())

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
if (strs.length == 0) return new ArrayList();
Map<String, List> ans = new HashMap<String, List>();

for (String s : strs) {
char[] ca = s.toCharArray();
Arrays.sort(ca);
String key = String.valueOf(ca);

if (!ans.containsKey(key)) ans.put(key, new ArrayList());
ans.get(key).add(s);
}
return new ArrayList(ans.values());
}
}

--

--