49. Group Anagrams
mediumCluster strings into anagram groups. Tests hash-map intuition plus the key insight that a sorted version of an anagram is the same for every member of its group.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Constraints
1 <= strs.length <= 10^40 <= strs[i].length <= 100strs[i] consists of lowercase English letters.
Examples
Example 1
strs = ["eat","tea","tan","ate","nat","bat"][["bat"],["nat","tan"],["ate","eat","tea"]]Example 2
strs = [""][[""]]Example 3
strs = ["a"][["a"]]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Two strings are anagrams iff they share a canonical form.
Hint 2
What canonical form? Sorted characters works: sort('eat') = 'aet' = sort('tea') = sort('ate').
Hint 3
Walk the input. For each string, compute its key (sorted chars or a 26-element frequency tuple). Append the original to map[key]. Return map.values().
Solution approach
Reveal approach
Hash map from canonical key to list of strings. For each input string, build a key — either the sorted character string ('eat' -> 'aet') or a count-of-each-letter tuple — and append the original string to map[key]. The first approach costs O(L log L) per string (for sorting); the second is O(L) where L is the string length. Return the map's values when done. Group order does not matter per the spec.
Complexity
- Time
- O(n * L log L)
- Space
- O(n * L)
Related patterns
- hash-map
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Meta
- Microsoft
- Uber
- Bloomberg
More Strings practice problems
- 3. Longest Substring Without Repeating Characters
- 5. Longest Palindromic Substring
- 6. Zigzag Conversion
- 14. Longest Common Prefix
- 20. Valid Parentheses
- 28. Find the Index of the First Occurrence in a String
- 58. Length of Last Word
- 76. Minimum Window Substring