BackmediumHashing Razorpay

Group Anagrams Together Solution

Problem Statement

Given an array of strings, group anagrams together.

Example 1
Input
['cats', 'acts', 'pots', 'stop', 'tops']
Output
[['cats', 'acts'], ['pots', 'stop', 'tops']]

Explanation: Step 1: Create a hashmap to store anagrams. Initialize an empty hashmap with default value as an empty list. Step 2: Iterate over each string in the input array. Sort the characters in the string and use it as a key in the hashmap. Step 3: Append the string to the corresponding list in the hashmap. Step 4: Return the values of the hashmap as a list of lists.

Example 2
Input
['enlist', 'silent', 'listen', 'tinsel']
Output
[['enlist', 'silent'], ['listen', 'tinsel']]

Explanation: Step 1: Create a hashmap to store anagrams. Initialize an empty hashmap with default value as an empty list. Step 2: Iterate over each string in the input array. Sort the characters in the string and use it as a key in the hashmap. Step 3: Append the string to the corresponding list in the hashmap. Step 4: Return the values of the hashmap as a list of lists.

Constraints

  • 1 <= n <= 10^4
  • Strings consist of lowercase English letters.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free