Group Anagrams
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.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Examples
Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation: "eat", "tea", and "ate" are all anagrams of each other. "tan" and "nat" are anagrams. "bat" has no anagram in the list.
Example 2
Input: strs = ["hhhhu","tttti","tttit","hhhuh"]
Output: [["hhhhu","hhhuh"],["tttti","tttit"]]
Explanation: "hhhhu" and "hhhuh" share the same character counts (4 h's and 1 u). "tttti" and "tttit" share the same counts (4 t's and 1 i).
Constraints
- -1 <= strs.length <= 10^4
- -0 <= strs[i].length <= 100
- -strs[i] consists of lowercase English letters.
Optimal Complexity
Time
O(n * k)
Space
O(n * k)
Practice this problem with an AI interviewer
TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.
Start a free interview