Group Anagrams Visualizer & Step-by-Step Algorithm Solution

Group strings together using sorted character keys in a hash map.

Category: arrays | Difficulty: Medium

Tags: Hash Map, Sorting, Categorization

Group Anagrams

Input Strings (strs)
i
eat
0
tea
1
tan
2
ate
3
nat
4
bat
5
Sorted Key → Result Group Index
(Empty Map)
100%
state
strN/A
sortedStringN/A
result groups0
Initialization
1/28
Explanation

Starting groupAnagrams function.

Source Code
1function groupAnagrams(strs) {
2 const map = new Map();
3 const result = [];
4 for (let i = 0; i < strs.length; i++) {
5 const sorted = strs[i].split("").sort().join("");
6 if (map.has(sorted)) {
7 result[map.get(sorted)].push(strs[i]);
8 } else {
9 map.set(sorted, result.length);
10 result.push([strs[i]]);
11 }
12 }
13 return result;
14}