NLeetCode Solutions
ProblemsPatternsStatistics
© 2026 Created by Trịnh Minh Nhật
GitHubLeetCode
Related posts
  • 217. Contains DuplicateEasy
  • 242. Valid AnagramEasy
  • 347. Top K Frequent ElementsMedium
  • 1. Two SumEasy
  • 13. Roman to IntegerEasy

49. Group Anagrams

Medium
ArrayHash TableStringSorting
Companies:
UberAmazonFacebookBloombergYelp
Answered: Mar 2, 2026
View on LeetCode

Problem Description

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Examples

Example 1

Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
  • There is no string in strs that can be rearranged to form "bat".
  • The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
  • The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.

Example 2

Input: strs = [""]
Output: [[""]]

Example 3

Input: strs = ["a"]
Output: [["a"]]

Constraints

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Solutions

Complexity Analysis

Time Complexity:O(m∗nlogn)

Where m is the number of strings in the input array and n is the maximum length of a string. Sorting each string takes O(nlog⁡n)O(n \log n)O(nlogn) time, and we do this for all m strings.

Space Complexity:O(m∗n)

In the worst case, all strings are anagrams of each other, and we store all n strings in a single group. The space required for the hash map is O(m∗n)O(m * n)O(m∗n) due to storing the sorted keys and the original strings.

In this approach, we use a hash map (or dictionary) to group the anagrams together. The key for the hash map is generated by sorting the characters of each string. Since anagrams will have the same sorted character sequence, they will be grouped under the same key in the hash map. After processing all strings, we return the values of the hash map, which are the groups of anagrams.

Complexity Analysis

Time Complexity:O(m∗n)

Where m is the number of strings in the input array and n is the maximum length of a string. For each string, we iterate through all its characters once to build the count array, which takes O(n)O(n)O(n) time. We do this for all m strings.

Space Complexity:O(m∗n)

In the worst case, all strings are anagrams of each other, and we store all n strings in a single group. The space required for the hash map is O(m∗n)O(m * n)O(m∗n) due to storing the count arrays and the original strings.

In this approach, instead of sorting the strings, we create a count array for each string that counts the occurrences of each character (assuming only lowercase English letters). The count array is then used as a key in the hash map to group anagrams together. Since anagrams will have the same character counts, they will be grouped under the same key in the hash map. After processing all strings, we return the values of the hash map, which are the groups of anagrams.

Conclusion

ApproachRatingTime ComplexitySpace ComplexityAdvantagesDisadvantages
Sorting Each String
O(m∗nlog⁡n)O(m * n \log n)O(m∗nlogn)O(m∗n)O(m * n)O(m∗n)Simple to understand and implement, works for any character setSlower due to sorting overhead per string
Character Count Array (Optimized Hash Map)
O(m∗n)O(m * n)O(m∗n)O(m∗n)O(m * n)O(m∗n)More efficient with linear time complexity per string, avoids sorting overheadOnly works when the character set is known and limited

The optimal approach for this problem is Solution 2: Character Count Array (Optimized Hash Map), which achieves O(m∗n)O(m * n)O(m∗n) time complexity by using a fixed-size array of 26 elements as a hash key instead of sorting. This approach is most suitable when dealing with strings that contain only lowercase English letters, as it avoids the O(nlog⁡n)O(n \log n)O(nlogn) sorting overhead per string and directly uses character frequency counts for grouping.


Previous27. Remove Element
Next70. Climbing Stairs
Related posts
  • 217. Contains DuplicateEasy
  • 242. Valid AnagramEasy
  • 347. Top K Frequent ElementsMedium
  • 1. Two SumEasy
  • 13. Roman to IntegerEasy
On this page
11 lines
1class Solution:
2 def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3 # Create a dictionary to hold the groups of anagrams
4 dict = defaultdict(list)
5
6 for s in strs:
7 # Sort the string to get the key for the anagram group, E.g., "eat" -> "aet"
8 sorted_s = "".join(sorted(s))
9 dict[sorted_s].append(s)
10
11 return list(dict.values())
14 lines
1class Solution:
2 def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3 # Create a dictionary to hold the groups of anagrams
4 dict = defaultdict(list)
5
6 for s in strs:
7 counts = [0] * 26 # Initialize a count array for each character
8
9 for char in s:
10 counts[ord(char) - ord('a')] += 1 # Increment the count for this character
11
12 dict[tuple(counts)].append(s) # Use the count array as a key to group anagrams
13
14 return list(dict.values())