BackmediumHashingFlipkartAdobe

Anagram Cluster Formation Solution

Problem Statement

Given an array of strings, group the anagrams together and return each group.

Example 1
Input
["eat","tea","tan","nat","bat"]
Output
[["eat","tea"],["tan","nat"],["bat"]]

Explanation: Step-by-step: First, we sort each string in the input array. Then, we group the strings by their sorted values. Finally, we return the groups of anagrams.

Example 2
Input
["cat","tac","dog","god"]
Output
[["cat","tac"],["dog","god"]]

Explanation: Step-by-step: First, we sort each string in the input array. Then, we group the strings by their sorted values. Finally, we return the groups of anagrams.

Constraints

  • 1 <= n <= 10^4
  • Strings consist of lowercase English letters.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Anagram Cluster Formation — Problem Statement & Solution Guide

HashingMediumHash Map / Grouping
TimeO(n*m*log(m))
|
SpaceO(n*m)

Problem Description

Given an array of strings, group the anagrams together and return each group.

Examples

Example 1

Input

["eat","tea","tan","nat","bat"]

Output

[["eat","tea"],["tan","nat"],["bat"]]

Explanation: Step-by-step: First, we sort each string in the input array. Then, we group the strings by their sorted values. Finally, we return the groups of anagrams.

Example 2

Input

["cat","tac","dog","god"]

Output

[["cat","tac"],["dog","god"]]

Explanation: Step-by-step: First, we sort each string in the input array. Then, we group the strings by their sorted values. Finally, we return the groups of anagrams.

Constraints

  • 1 <= n <= 10^4
  • Strings consist of lowercase English letters.

Optimal Approach & Strategy

Use a HashMap where the key is the sorted string and the value is a list of original strings. Iterate, sort each string, group by key. Time O(N * K log K), Space O(N * K).

Brute Force Approach

Compare every string with every other string. Time O(N^2 * K).

Verified Code Solutions

JavaScript Solution
Time: O(n*m*log(m))
function groupAnagrams(strs) {
   const anagrams = {};
   for (const str of strs) {
      const sortedStr = str.split('').sort().join('');
      if (!anagrams[sortedStr]) anagrams[sortedStr] = [];
      anagrams[sortedStr].push(str);
   }
   return Object.values(anagrams);
}

Asked in Top Tech Interviews

FlipkartAdobe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.