Challenge: Group Anagrams

This challenge is about finding the anagrams in an array.

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Problem statement

Given an array of strings that contains anagrams, write a function to print those anagrams.

Input

The input is an array of strings. Remember that spaces count as characters! So " abc" and “cab” are technically not anagrams since " abc" has spaces which “cab” does not.

Output

The output is a string where all the anagrams are grouped together.

Sample input

"cat", "dog", "tac", "god", "act",  "tom marvolo riddle ","abc", "def",  "cab", "fed", "clint eastwood ", "i am lord voldemort", "elvis", "old west action",  "lives" 

Sample output

"[cat, tac, act][abc, cab][def, fed][clint eastwood , old west action][tom marvolo riddle , i am lord voldemort][elvis, lives][dog, god]" 

Note: The sequence in the groups should be the same in the output as in the input. For example, “cat” should come before “tac” as it does in the input string.

Coding exercise

First, take a close look and design a step-by-step algorithm. Then jump to implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the hint and solution provided in the code tab. Good Luck!

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.