DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 49. Group Anagrams

Using Sorting

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
    let res = new Map()

    for (let s of strs) {
        const key = s.split('').sort().join('')
        if (!res.has(key)) {
            res.set(key, []);
        }
        res.get(key).push(s);
    }
    return Array.from(res.values());

};

Using Sorting takes O(nlogn * m) time complexity

We can optimize to O(n * m) with Hashmap

Enter fullscreen mode Exit fullscreen mode

Using HashMap

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
    let res = new Map()

    for (let s of strs) {
        const count = new Array(26).fill(0);
        for (c of s) {
            count[c.charCodeAt(0) - "a".charCodeAt(0)] += 1;
        }
        const key = count.join(',')
        if (!res.has(key)) {
            res.set(key, []);
        }
        res.get(key).push(s);
    }
    return Array.from(res.values());
};
Enter fullscreen mode Exit fullscreen mode

charCodeAt(index)

  • Returns the ASCII/Unicode value of the character at the given index in a string.
  • Example: "a".charCodeAt(0) → 97 (Unicode of 'a').

1️⃣ res.get(key).push(s);

  • Retrieves the array stored at key in the Map.
  • Pushes s into the array in place (modifies existing array).
  • No need for res.set(key, updatedArray) because arrays are reference types.

2️⃣ Array.from(res.values())

  • res.values() returns an iterator of all values in the Map.
  • Array.from() converts the iterator into a normal array.
  • Ensures the function returns a proper string[][] instead of an iterator.

Top comments (0)