AlgoInsight

DSA problem

Group Anagrams

MediumHash TablesPattern: Hash Maptop75FreeAmazonFacebookMicrosoftGoogleUberBloomberg

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

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Two strings are anagrams of each other if and only if their sorted character sequences are identical, or equivalently if they have the exact same multiset of characters.

The goal is to partition the input list into groups such that every string within a group is an anagram of every other string in that group, and no two strings from different groups are anagrams. Each group is returned as a list of the original strings.

Examples

Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation: "eat", "tea", and "ate" all share the letters a, e, t. "tan" and "nat" share a, n, t. "bat" stands alone. The order of groups and of strings within a group does not matter.
Example 2
Input: strs = [""]
Output: [[""]]
Explanation: A single empty string forms its own group.
Example 3
Input: strs = ["a"]
Output: [["a"]]
Explanation: A single one-character string forms its own group.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

hash-tablestringsorting

Browse all DSA problems