
Problem
Solution
Submissions
Group Anagrams
Certification: Intermediate Level
Accuracy: 100%
Submissions: 1
Points: 10
Write a JavaScript program to group anagrams together from an array of strings. Two strings are anagrams if they contain the same characters with the same frequencies but in different order. Return an array of arrays where each sub-array contains strings that are anagrams of each other.
Example 1
- Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
- Output: [["eat","tea","ate"],["tan","nat"],["bat"]]
- Explanation:
- "eat", "tea", and "ate" are anagrams because they all contain the same letters: e, a, t.
- "tan" and "nat" are anagrams because they both contain the letters: t, a, n.
- "bat" stands alone as it has no anagrams in the input array.
- Each group of anagrams is returned as a separate sub-array.
Example 2
- Input: strs = ["abc", "bca", "cab", "xyz", "zyx"]
- Output: [["abc","bca","cab"],["xyz","zyx"]]
- Explanation:
- "abc", "bca", and "cab" are anagrams as they contain the same letters: a, b, c.
- "xyz" and "zyx" are anagrams as they contain the same letters: x, y, z.
- Two groups are formed based on the anagram relationships.
- "abc", "bca", and "cab" are anagrams as they contain the same letters: a, b, c.
Constraints
- 1 ≤ strs.length ≤ 10^4
- 0 ≤ strs[i].length ≤ 100
- strs[i] consists of lowercase English letters only
- Time Complexity: O(n * k * log k) where n is number of strings and k is maximum length
- Space Complexity: O(n * k)
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use a hash map to group strings by their sorted character representation
- For each string, sort its characters to create a key
- Strings with the same sorted key are anagrams
- Store arrays of anagrams using the sorted string as the key
- Convert the hash map values to the final result array
- Consider edge cases like empty strings and single character strings