LeetCode - Algorithms - 49. Group Anagrams

Problem

49. Group Anagrams

Given an array of strings, group anagrams together.

JavaScript

solution by Joan Indiana Lyness

Algorithms 101: Group Anagrams in JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @param {string[]} strs
* @return {string[][]}
*/
var groupAnagrams = function(strs) {
var m = {};
for(var i=0;i<strs.length;i++) {
var s = strs[i];
var c = s.split("").sort();
m[c]?m[c].push(s):m[c]=[s];
}
var r = [];
var keys = Object.keys(m);
for(var k=0; k<keys.length; k++) {
r.push( m[keys[k]] );
}
return r;
};

Submission Detail

  • 101 / 101 test cases passed.
  • Runtime: 144 ms, faster than 32.01% of JavaScript online submissions for Group Anagrams.
  • Memory Usage: 45.6 MB, less than 34.78% of JavaScript online submissions for Group Anagrams.

Java

translation from solution of Joan Indiana Lyness

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
26
27
28
29
30
31
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;

class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> list = new ArrayList<List<String>>();
Map<String, List<String>> map = new HashMap<String, List<String>>();
String s;
char[] c;
String key;
for (int i = 0; i < strs.length; i++) {
s = strs[i];
c = s.toCharArray();
Arrays.sort(c);
key = new String(c);
if (map.containsKey(key)) {
map.get(key).add(s);
} else {
List<String> glist = new ArrayList<String>();
glist.add(s);
map.put(key, glist);
}
}

list.addAll(map.values());
return list;
}
}

Submission Detail

  • 101 / 101 test cases passed.
  • Runtime: 9 ms, faster than 83.05% of Java online submissions for Group Anagrams.
  • Memory Usage: 40.8 MB, less than 96.49% of Java online submissions for Group Anagrams.

ref