Group Anagrams
Medium Difficulty
Problem
Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order. An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.
First Solution
class Solution { /** * @param {string[]} strs * @return {string[][]} */ groupAnagrams(strs) { let sorted = []; for (let s of strs) { sorted.push(s.split('').sort().join('')); }
let map = new Map();
for (let i = 0; i < sorted.length; i++) { let bucket = map.get(sorted[i]) || []; bucket.push(i); map.set(sorted[i], bucket); }
let solution = []; let runningIndex = 0 for (let [key, ele] of map) { for (let index of ele) { let bucket = solution[runningIndex] || []; bucket.push(strs[parseInt(index)]); solution[runningIndex] = bucket; } runningIndex++; } return solution; }}
Thoughts/Notes
This problem is honestly not that different from the Easy Difficulty variant of this problem. The main crux of this problem is to map out the potential anagrams and their corresponding matching indices, then returning that list. One tricky part of this is with how the “index” storage part of this works. Due to the quirk’s of JavaScript’s map here, the index is stored as a string and not a number, so it’s important to parse that back into an integer when doing the strs[] index.