Leet Code – 49. Group Anagrams

Given an array of strings, group anagrams together.

For example, given:["eat", "tea", "tan", "ate", "nat", "bat"]
Return:

Note: All inputs will be in lower-case.

Solution – Two strings are anagrams if both have same characters and count of each character to be same. In other words, they are shuffled version of one another. example – eat, tea, ate are anagrams

Actual definition – https://en.wikipedia.org/wiki/Anagram

If we sort anagrams then they will output same string.

Algorithm –

  1. iterate over an array of strings.
  2. initiate an empty object res to maintain a group of anagrams
  3. for each string check if it sorted version exists in res
  4. if sorted value exists, push the string corresponding to sorted value
  5. if it does not exist, add sorted value to res and then push the string corresponding to sorted value.
  6. Iterate over each property of res and then sort and push corresponding array to result set.

 

 

Run Code Result:
Your input

Your answer

Expected answer

Leave a Reply

Your email address will not be published. Required fields are marked *