Practice Problem

Group Anagrams

Difficulty: Medium

Group an array of strings so that anagrams appear together, using a hash map with sorted-character keys.

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, using all the original letters exactly once.

Examples

Example 1:

Input: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]]
Explanation: "eat", "tea", and "ate" are anagrams of each other.
"tan" and "nat" are anagrams. "bat" has no anagram in the list.

Example 2:

Input: strs = [""]
Output: [[""]]
Explanation: The single empty string is its own group.

Example 3:

Input: strs = ["a"]
Output: [["a"]]

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters only.

Expected Complexity

  • Time: O(n * k log k) where n is the number of strings and k is the maximum string length
  • Space: O(n * k) to store all strings in the hash map
MEDIUM
Arrays
Strings
Hash Map / Dictionary
Sorting
Anagrams
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium