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"]]
Example 2
Input: strs = [""] Output: [[""]]
Example 3
Input: strs = ["a"] Output: [["a"]]
๐ 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()); };
๐ How It Works
-
Sort Each String:
- For each string in
strs
, sort its characters alphabetically. - Use the sorted string as the key in the hash map.
- For each string in
-
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.
-
Return Groups:
- Extract the grouped arrays from the map and return them.
๐ Complexity Analysis
-
Time Complexity:
- Sorting each string:
O(mโ nlogn)
, wheren
is the average string length andm
is the number of strings. - Inserting into the hash map:
O(m)
. - Total:
O(mโ nlogn)
.
- Sorting each string:
-
Space Complexity:
- The hash map stores
O(m)
keys and values.
- The hash map stores
๐ Dry Run
Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
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()); };
Complexity (Character Count Approach)
-
Time Complexity: O(mโ n), where
m
is the number of strings andn
is the average string length.- Counting characters is
O(n)
.
- Counting characters is
Space Complexity:
O(m)
for the hash map.
โจ Pro Tips for Interviews
-
Highlight Trade-Offs:
- Sorting strings is simpler to implement but slower than using character counts.
-
Edge Cases:
- Empty strings:
[""]
. - Single-character strings:
["a", "b", "a"]
.
- Empty strings:
๐ 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! ๐
Top comments (1)
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!