DEV Community

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

Posted on

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

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!