Tutorialspoint
Problem
Solution
Submissions

Group Anagrams

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program that groups a list of strings into anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, using all the original letters exactly once.

Example 1
  • Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
  • Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
  • Explanation:
    • Step 1: We identify which strings are anagrams of each other.
    • Step 2: "eat", "tea", and "ate" all have the same characters, so they form one group.
    • Step 3: "tan" and "nat" have the same characters, so they form another group.
    • Step 4: "bat" doesn't share the same characters with any other string, so it forms its own group.
    • Step 5: We return the grouped anagrams as a list of lists.
Example 2
  • Input: strs = [""]
  • Output: [[""]]
  • Explanation:
    • Step 1: There is only one string in the input and it's an empty string.
    • Step 2: The empty string is grouped by itself.
    • Step 3: We return the empty string as its own group.
Constraints
  • 1 <= strs.length <= 100
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters
  • All inputs will be valid
  • Time Complexity: O(n * k), where n is the length of strs and k is the maximum length of a string in strs
  • Space Complexity: O(n * k)
StringsEYDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a hash table to group anagrams together.
  • For each string, create a key that represents its character frequency.
  • One efficient way to create a key is to sort the characters of each string.
  • All anagrams will have the same sorted string representation.
  • Group strings by their sorted representation.

Steps to solve by this approach:

 Step 1: Create a function to sort characters in a string alphabetically.
 
 Step 2: Define a structure to hold groups of anagrams with their sorted key.
 Step 3: For each input string, sort it to get the anagram key.
 Step 4: Find or create a group with the matching key.
 Step 5: Add the original string to the appropriate group.
 Step 6: Format and return the groups of anagrams.
 Step 7: Free allocated memory to prevent memory leaks.

Submitted Code :