Group Anagrams
Medium
Array
Hash Table
String
Sorting
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a string formed by rearranging the letters of another string, using all the original letters exactly once.
Example 1
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation: There is no string in strs that can be rearranged to form "bat". The strings "nat" and "tan" are anagrams. The strings "ate", "eat", and "tea" are anagrams.
Example 2
Input: strs = [""]
Output: [[""]]
Example 3
Input: strs = ["a"]
Output: [["a"]]

Constraints

  • 1 <= strs.length <= 10⁴
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.
Time Complexity
O(n·k log k)
Space Complexity
O(n·k)
14
Case 1
Input: ["eat","tea","tan","ate","nat","bat"]
Expected: [[bat],[ate,eat,tea],[nat,tan]]
Case 2
Input: ["a"]
Expected: [[a]]
Case 3
Input: ["ddd","dad","add"]
Expected: [[add,dad],[ddd]]