group-anagrams

Problem

Group Anagrams

Problem Description

Given an array of strings, group anagrams together.

Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Note:

All inputs will be in lowercase.
The order of your output does not matter.

Solution 1

  1. sorted string alphabetically

  2. sorted string as key, if after sorted, string is the same, put original string into list, group with the same sorted string.

  3. get result new ArrayList<>(map.values());

Time complexity:

Solution 2

From solution 1, we realize that if with the same anagram group, sorted string has the same value. How can we get the unique key without sorting original string. hash string, since all characters in string will be the same, calculate each character frequency into char array, get char array string value as key.

Time complexity:

Last updated

Was this helpful?