Skip to content
MediumStringsFree practice

Group Anagrams

Asked atamazongooglefacebookmicrosoftuber

01 · Problem

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.

02 · Examples

Example 01
Input
strs = ["eat","tea","tan","ate","nat","bat"]
Output
[["bat"],["nat","tan"],["ate","eat","tea"]]

"eat", "tea", and "ate" are all anagrams of each other. "tan" and "nat" are anagrams. "bat" has no anagram in the list.

Example 02
Input
strs = ["abc","bca","cab","xyz","zyx"]
Output
[["abc","bca","cab"],["xyz","zyx"]]

"abc", "bca", and "cab" belong together because they contain the same letters. "xyz" and "zyx" form the second anagram group.

03 · Constraints

  • 011 <= strs.length <= 104
  • 020 <= strs[i].length <= 100
  • 03strs[i] consists of lowercase English letters.

04 · Optimal complexity

Time
O(n * k)
Space
O(n * k)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.