Group Anagrams

Given a sequence of words, print all anagrams together – Anagrams Group Problem

Given an array of strings strs, group all anagrams together into sublists. You may return the output in any order.

An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.

Anagrams Group for string

Constraints:

  • 1 <= strs.length <= 1000
  • 0 <= strs[i].length <= 100
  • strs[i] is made up of lowercase English letters.

Given a sequence of words, print all anagrams together - Anagrams Group Solution

Recommendation – You should aim for a solution with O(m * n) time and O(m) space, where m is the number of strings and n is the length of the longest string.

Hints for solving problems

Hint 1 :

A naive solution would be to sort each string and group them using a hash map. This would be an O(m * nlogn) solution. Though this solution is acceptable, can you think of a better way without sorting the strings?

Hint 2:

By the definition of an anagram, we only care about the frequency of each character in a string. How is this helpful in solving the problem?

Hint 3:

We can simply use an array of size O(26), since the character set is a through z (26 continuous characters), to count the frequency of each character in a string. Then, we can use this array as the key in the hash map to group the strings.

There are mainly 2 approach to solve this problem 

  1. Sorting Method
  2. Hash Table Method

1. Sorting Method

This method sort each word in the list, use the sorted word as a key in a hash map, and group words with the same sorted key together.

  • Time complexity: O(m*nlog n)
  • Space complexity: O(m*n)

where m is the number of strings and n is the length of the longest string.

Code

2. Hash Table Method

This method use a hash table with a character frequency count as the key to group words that have the same character counts into the same group.

  • Time complexity: O(m*n)
  • Space complexity: O(m)

where m is the number of strings and n is the length of the longest string.

Code

More Articles