Group Anagrams
Updated
Problem statement
You are given an array of strings strs. Put the strings that are anagrams of each other into the same group, and return the list of groups.
Two strings are anagrams when one can be made from the other by changing the order of its letters, so both use the same letters the same number of times. For example, "eat", "tea" and "ate" are anagrams. Every string of strs goes into exactly one group. If a string appears more than once in strs, it appears that many times in its group.
Return the groups in this fixed order: sort the strings inside each group in dictionary order, then sort the groups in dictionary order of their first string. In dictionary order, a string comes before every longer string that starts with it, so the empty string "" comes first.
Function
groupAnagrams(strs: String[]) → List<List<String>>Examples
Example 1
strs = ["eat","tea","tan","ate","nat","bat"]return = [["ate","eat","tea"],["bat"],["nat","tan"]]"eat", "tea" and "ate" use the letters a, e and t once each, so they form one group. "tan" and "nat" form another, and "bat" is alone. Each group is sorted, and the groups are ordered by their first strings "ate", "bat" and "nat".
Example 2
strs = [""]return = [[""]]The only string is empty, so there is one group holding it.
Example 3
strs = ["abc","cab","ab","ba","ab"]return = [["ab","ab","ba"],["abc","cab"]]"ab" appears twice and "ba" once, so their group holds all three. "abc" and "cab" form the second group. "ab" comes before "abc" because it is the start of it, so the group starting with "ab" is first.
Constraints
1 <= strs.length <= 10000 <= strs[i].length <= 100strs[i]consists of lowercase English letters.
More Amazon Web Services Onsite Interview questions
- Longest Substring with At Most K Distinct CharactersONSITE INTERVIEW · Seen Nov 2026
- Fixed-K Kth Largest StreamONSITE INTERVIEW · Seen Aug 2026
- Logger Rate LimiterONSITE INTERVIEW · Seen Aug 2026
- Recent Hit CounterONSITE INTERVIEW · Seen Aug 2026
- Spreadsheet Formula DependenciesONSITE INTERVIEW · Seen Aug 2026
Similar questions at other companies
- Longest Consecutive Login StreakAmazon · ONSITE INTERVIEW
- Group AnagramsMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Find Duplicate Element PairsGoogle · ONSITE INTERVIEWGoogle interview questions
- Deep Merge with a Conflict ResolverAutodesk · ONSITE INTERVIEWAutodesk interview questions
- Group Duplicate Files by ContentPostman · ONSITE INTERVIEWPostman interview questions
- Group AnagramsGoldman Sachs · ONSITE INTERVIEWGoldman Sachs interview questions
- Group AnagramsMotive · PHONE SCREEN · ONSITE INTERVIEWMotive interview questions
- Group AnagramsBloomberg LP · PHONE SCREEN · ONSITE INTERVIEWBloomberg LP interview questions
- Group AnagramsExpedia · ONSITE INTERVIEWExpedia interview questions
- Group AnagramsAkuna Capital · ONSITE INTERVIEWAkuna Capital interview questions