Tutorialspoint
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.
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)
StringsHash MapTutorialspointIBM
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a Map to store groups of anagrams using sorted strings as keys.

 Step 2: Iterate through each string in the input array.
 Step 3: For each string, sort its characters alphabetically to create a unique key.
 Step 4: Check if this sorted key already exists in the map.
 Step 5: If the key exists, add the current string to the existing group.
 Step 6: If the key doesn't exist, create a new group with the current string.
 Step 7: Convert the map values to an array and return the grouped anagrams.

Submitted Code :