Skip to main content

Group Anagrams - Solution & Explanation

MediumArrayHash TableStringSorting16 min readAsked at: Amazon, Microsoft, Apple +84
Practice this problem

Problem Statement

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

 

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.

Approach Overview

Problem Overview: You receive an array of strings and must group words that are anagrams of each other. Two strings belong in the same group if they contain the same characters with the same frequency, regardless of order.

Approach 1: Hash Map + Character Frequency (O(n * k))

This method builds a frequency signature for every string. For each word, count how many times each letter appears using a fixed-size array of length 26. Convert that frequency array into a hashable key (for example a tuple or string) and store the word in a hash map where the key represents the character distribution. Words with identical frequency signatures are anagrams and end up in the same bucket.

The key insight: anagrams share identical character counts. Instead of sorting characters, you directly encode the frequency of each letter. Each string requires a single pass to build its signature, giving O(n * k) time where n is the number of strings and k is the average string length. Space complexity is O(n * k) due to storing grouped strings in the map. This approach heavily relies on a hash table for constant-time grouping.

Approach 2: Sorting Characters as Key (O(n * k log k))

A simpler and very common solution sorts each string alphabetically and uses the sorted string as the key in a hash map. For example, "eat", "tea", and "ate" all become "aet" after sorting. When you iterate through the input, sort the characters of each word, then append the original word to the list stored under that sorted key.

This approach is easy to implement and works well for interview settings. Sorting each word takes O(k log k), so the total runtime becomes O(n * k log k). Space complexity remains O(n * k) for storing groups and keys. It combines string manipulation with sorting and hash-based grouping.

Recommended for interviews: The sorting-based hash map approach is the most widely expected solution because it is concise and easy to reason about. Many candidates start there. The frequency-count approach is more optimal asymptotically since it avoids sorting and runs in O(n * k). Showing both approaches demonstrates solid understanding of hashing, string manipulation, and algorithmic tradeoffs.

Approach 1: Approach 1: Dynamic Programming

This approach involves using dynamic programming to store solutions to subproblems in a table and build up to the solution of the original problem. By doing so, we can avoid redundant calculations and achieve a more efficient solution.

The dynamic programming approach in C involves initializing a dp array to store intermediate results and filling it up based on the recurrence relation derived from the problem's requirements.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n)

Space Complexity: O(n)

Try this approach in the editor →

Approach 2: Approach 2: Greedy Algorithm

A greedy algorithm is an approach that constructs a solution by choosing the best option at each step. This approach may not always yield the optimal global solution, but for certain problems, especially those with optima formed by greedy choices, it can be very efficient.

This C solution applies a greedy technique where at each step, the locally optimal choice is made with hopes of finding the global optimum.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n) /* or other depending on the specific problem */

Space Complexity: O(1) /* if in-place, depending on conditions */

Try this approach in the editor →

Approach 3: Hash Table

  1. Traverse the string array, sort each string in character dictionary order to get a new string.
  2. Use the new string as key and [str] as value, and store them in the hash table (HashMap<String, List<String>>).
  3. When encountering the same key during subsequent traversal, add it to the corresponding value.

Take strs = ["eat", "tea", "tan", "ate", "nat", "bat"] as an example. At the end of the traversal, the state of the hash table is:

key value
"aet" ["eat", "tea", "ate"]
"ant" ["tan", "nat"]
"abt" ["bat"]

Finally, return the value list of the hash table.

The time complexity is O(ntimes ktimes log k), where n and k are the lengths of the string array and the maximum length of the string, respectively.

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Approach 4: Counting

We can also change the sorting part in Solution 1 to counting, that is, use the characters in each string s and their occurrence times as key, and use the string s as value to store in the hash table.

The time complexity is O(ntimes (k + C)), where n and k are the lengths of the string array and the maximum length of the string, respectively, and C is the size of the character set. In this problem, C = 26.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Approach 1: Dynamic Programming

Time Complexity: O(n)

Space Complexity: O(n)

Approach 2: Greedy Algorithm

Time Complexity: O(n log n) /* or other depending on the specific problem */

Space Complexity: O(1) /* if in-place, depending on conditions */

Hash Table—
Counting—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Hash Map + Character FrequencyO(n * k)O(n * k)When optimizing runtime and alphabet size is fixed (e.g., lowercase letters)
Hash Map + Sorted String KeyO(n * k log k)O(n * k)General interview solution; simplest and most commonly implemented

Video Solution

Group Anagrams - Categorize Strings by Count - Leetcode 49 • NeetCode • 868,210 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Group Anagrams easy or hard?
Group Anagrams is generally considered a medium-level problem. The challenge comes from recognizing that anagrams share a canonical representation and using hashing to group them efficiently instead of comparing every pair of strings.
How to solve Group Anagrams in O(n)?
Strict O(n) is not possible because you must inspect each character of every string. However, using a character frequency signature avoids sorting and achieves O(n * k) time, where k is the average string length. Each string is processed once to build a 26-character frequency array used as the hash key.
What is the best approach for Group Anagrams?
The most common approach uses a hash map where the key is the sorted version of each string. After sorting characters in a word, all anagrams produce the same key and are grouped together. This runs in O(n * k log k) time where n is the number of strings and k is the average string length.
What data structure is used in Group Anagrams?
The core data structure is a hash map (dictionary). The key represents the canonical form of the string, such as a sorted string or character frequency signature, and the value stores a list of words that match that key.
What is the time complexity of Group Anagrams?
The typical sorting-based solution runs in O(n * k log k) time because each string must be sorted before grouping. A more optimized approach counts character frequencies and builds a signature key, reducing complexity to O(n * k). Both approaches use O(n * k) space to store grouped strings.
Group Anagrams Python or Java solution approach?
In Python or Java, iterate through the array of strings, compute a key for each string (usually by sorting characters), and store the word in a HashMap or dictionary under that key. After processing all words, return the values of the map as grouped anagrams.
Is Group Anagrams asked at Google, Amazon, or Meta?
Group Anagrams is a common hashing and string manipulation problem frequently asked in coding interviews at companies like Amazon, Google, Meta, and Microsoft. Interviewers use it to evaluate understanding of hash maps, string processing, and algorithmic optimization.

Ready to solve this problem?

Practice Group Anagrams with our built-in code editor and test cases.

Practice on FleetCode