Skip to content

Commit ba6c910

Browse files
committed
Added Group Anagrams - Medium
1 parent 1a894f2 commit ba6c910

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(n * s log s) where n is the number of strings and s
2+
// is the length of the longest string
3+
// Space: O(ns)
4+
class Solution {
5+
public List<List<String>> groupAnagrams(String[] strs) {
6+
List<List<String>> anagrams = new ArrayList<>();
7+
Map<String, List<String>> map = new HashMap<>();
8+
for (String str : strs) {
9+
char[] sorted = str.toCharArray();
10+
Arrays.sort(sorted);
11+
String sortedStr = new String(sorted);
12+
if (!map.containsKey(sortedStr)) {
13+
map.put(sortedStr, new ArrayList<String>());
14+
}
15+
// Add to the list of anagrams for this sorted key
16+
map.get(sortedStr).add(str);
17+
}
18+
anagrams.addAll(map.values());
19+
return anagrams;
20+
}
21+
}

0 commit comments

Comments
 (0)