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.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong Ā· web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video šŸŒ¶ļøšŸ”„

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

šŸ‘‹ Kindness is contagious

If this article connected with you, consider tapping ā¤ļø or leaving a brief comment to share your thoughts!

Okay