AlgoMaster Logo

Group Anagrams

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Sorting Each Word

Intuition:

The first idea is to use the property that if two strings are anagrams of each other, their sorted form will be the same. By sorting each string and using it as a key, we can group the words that are anagrams together.

  1. Iterate over the list of strings.
  2. Sort each string and use it as a key in a hashmap where the value will be a list of strings.
  3. Finally, return all the values of the hashmap that represent grouped anagrams.

Code:

2. Counting Characters

Intuition:

Instead of sorting, we can use the frequency of characters as a key. If two strings are anagrams, they will have the same frequency distribution of characters.

  1. Use an array of size 26 to count the frequency of each character for each string because all characters are lowercase.
  2. Convert this frequency array to a unique string and use it as a key in a hashmap.
  3. Group strings with the same frequency distribution together.

Code: