Group Anagrams Together

You have been given an array/list of strings 'STR_LIST'. You are supposed to return the strings as groups of anagrams such that strings belonging to a particular group are anagrams of one another.

Note :
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase. We can generalize this in string processing by saying that an anagram of a string is another string with the same quantity of each character in it, in any order.
Example:
{ “abc”, “ged”, “dge”, “bac” } 
In the above example the array should be divided into 2 groups. The first group consists of { “abc”, “bac” } and the second group consists of { “ged”, “dge” }.
Input Format:
The first line contains a single integer ‘T’ denoting the number of test cases. The test cases are as follows.

The first line of each test case contains a single integer ‘N’ denoting the number of strings.

The next line contains 'N' single space-separated strings.
Output Format :
For each test case/query, print the anagrams belonging to the same group in a single line, where all the anagrams are separated by a single space, and each group will be printed in a separate line.

The output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5
1 <= N <= 1000
1 <= |STR_LIST[i]| <= 100
“STR_LIST[i]” contains only lowercase english letters.

Where ‘T’ denotes the number of test cases, ‘N’ denotes the number of strings, and |STR_LIST[i]| denotes the length of the i’th string.

Time Limit: 1 sec.
CodingNinjas
author
2y
Sorting based Approach

The idea behind this approach is that two or more than two strings are anagrams if and only if their sorted strings are equal. So we will use a HashMap, let’s say “anagramGroup”,...read more

CodingNinjas
author
2y
Categorize by Count

The key idea behind this approach is that we can transform each string into a string representing the character count. We will use an array “frequency", of size 26 such that each el...read more

CodingNinjas
author
2y
Trie based Approach

The idea is to sort each string and insert it into the trie. Each node of trie will have an array to store the indexes of the string ending at that node. Using a trie will improve t...read more

Add answer anonymously...
Goldman Sachs Analyst Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter