DEV Community

Cover image for LeetCode Challenge: 49. Group Anagrams - JavaScript Solution πŸš€
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on

3 1 1 1 1

LeetCode Challenge: 49. Group Anagrams - JavaScript Solution πŸš€

Top Interview 150

The Group Anagrams problem involves grouping words that are anagrams of each other. Let’s solve LeetCode 49: Group Anagrams step by step.


πŸš€ Problem Description

Given an array of strings strs, group all strings that are anagrams.

An anagram is a word or phrase formed by rearranging the letters of another. Both strings must have the same characters in the same frequencies.


πŸ’‘ Examples

Example 1

Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]  
Output: [["bat"], ["nat", "tan"], ["ate", "eat", "tea"]]
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: strs = [""]  
Output: [[""]] 
Enter fullscreen mode Exit fullscreen mode

Example 3

Input: strs = ["a"]  
Output: [["a"]]
Enter fullscreen mode Exit fullscreen mode

πŸ† JavaScript Solution

The key idea is to use a hash map to group anagrams. Each anagram has the same sorted character sequence, which we can use as the key.


Implementation

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

    for (let str of strs) {
        const sortedStr = str.split("").sort().join("");


        if (!map.has(sortedStr)) {
            map.set(sortedStr, []);
        }
        map.get(sortedStr).push(str);
    }

    return Array.from(map.values());
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Sort Each String:

    • For each string in strs, sort its characters alphabetically.
    • Use the sorted string as the key in the hash map.
  2. Group Strings by Key:

    • If the sorted string is not already a key in the map, add it with an empty array.
    • Append the original string to the array corresponding to the key.
  3. Return Groups:

    • Extract the grouped arrays from the map and return them.

πŸ”‘ Complexity Analysis

  • Time Complexity:

    • Sorting each string: O(mβ‹…nlogn), where n is the average string length and m is the number of strings.
    • Inserting into the hash map: O(m).
    • Total: O(mβ‹…nlogn).
  • Space Complexity:

    • The hash map stores O(m) keys and values.

πŸ“‹ Dry Run

Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Dry Run

Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]


Follow-Up: Faster Grouping Using Character Count

Instead of sorting strings (which costs O(nlogn)), we can use the character count as the key.


Implementation

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

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

        for (let char of str) {
            charCount[char.charCodeAt(0) - "a".charCodeAt(0)]++;
        }

        const key = charCount.join("#");

        if (!map.has(key)) {
            map.set(key, []);
        }
        map.get(key).push(str);
    }

    return Array.from(map.values());
};

Enter fullscreen mode Exit fullscreen mode

Complexity (Character Count Approach)

  • Time Complexity: O(mβ‹…n), where m is the number of strings and n is the average string length.

    • Counting characters is O(n).
  • Space Complexity: O(m) for the hash map.


✨ Pro Tips for Interviews

  1. Highlight Trade-Offs:

    • Sorting strings is simpler to implement but slower than using character counts.
  2. Edge Cases:

    • Empty strings: [""].
    • Single-character strings: ["a", "b", "a"].

πŸ“š Learn More

Check out the full explanation and code walkthrough on my previous Dev.to post:
πŸ‘‰ Valid Anagram - JavaScript Solution

What’s your preferred method to solve this problem? Let’s discuss! πŸš€


Study

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo πŸ“Šβœ¨

Top comments (1)

Collapse
 
rahulgithubweb profile image
Rahul Kumar Barnwal β€’

Follow Me on GitHub πŸš€

If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.

Don't forget to follow for more updates!

Jetbrains Survey

Calling all developers!

Participate in the Developer Ecosystem Survey 2025 and get the chance to win a MacBook Pro, an iPhone 16, or other exciting prizes. Contribute to our research on the development landscape.

Take the survey

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️