Skip to main content

group-anagram

Link: https://leetcode.com/problems/group-anagrams/description/

  • The concept here is make unique key from each string that represent the string even if the character are shuffle.
  • store the key with string in map or object i.e. hashmap
function groupAnagrams(strs) {
let ans = strs.reduce((acc, val) => {
let count = Array(26).fill(0); // making array of 26 length fill with 0. a[0] -> a, a[1] -> b
for (const char of val) {
count[char.charCodeAt(0) - "a".charCodeAt(0)]++; // increment the count each time the character is found
}
const key = count.join("#"); // making a unique key by joining array

if (!acc[key]) {
acc[key] = [];
}
acc[key].push(val);
return acc;
}, {});
return Object.values(ans);
}

Solution using map

var groupAnagrams = function (strs) {
const hashMap = new Map();

for (const str of strs) {
let numericalRepresentationOfStrings = new Array(26).fill(0);

for (const char of str) {
let charValue = char.charCodeAt(0) - 97;

numericalRepresentationOfStrings[charValue]++;
}

let key = numericalRepresentationOfStrings.join(",");

let value = hashMap.get(key) || [];
value.push(str);

hashMap.set(key, value);
}

let result = [];
for (const value of hashMap.values()) {
result.push(value);
}

return result;
};