FastPrepGroup Anagrams
Problem · String

Group Anagrams

Learn this problem
MediumJFrog logoJFrogFULLTIMEPHONE SCREEN

Problem statement

Given an array of strings strs, group together the strings that are anagrams of one another.

Two strings are anagrams when they contain the same letters with the same multiplicities. For deterministic output, sort the strings inside each group lexicographically, then sort the groups lexicographically by their first string.

Function

groupAnagrams(strs: String[]) → String[][]

Examples

Example 1

strs = ["eat","tea","tan","ate","nat","bat"]return = [["ate","eat","tea"],["bat"],["nat","tan"]]

Each anagram group is sorted internally, then the groups are ordered by ate, bat, and nat.

Example 2

strs = [""]return = [[""]]

The empty string has an all-zero letter signature and forms one group.

Example 3

strs = ["ab","ba","abc","cab","bca","x"]return = [["ab","ba"],["abc","bca","cab"],["x"]]

Each group and the list of groups use the required lexicographic order.

Constraints

  • 1 <= strs.length <= 10000.
  • 0 <= strs[i].length <= 100.
  • The total number of characters across all strings is at most 100000.
  • Every string contains only lowercase English letters.
drafts saved locally
public String[][] groupAnagrams(String[] strs) {
    // TODO: group and order the anagrams.
}
strs["eat","tea","tan","ate","nat","bat"]
expected[["ate", "eat", "tea"], ["bat"], ["nat", "tan"]]
checking account