Imagine you have a collection of words scattered around, and you need to organize them by their anagram groups. Two strings are anagrams if they contain the exact same characters with the same frequency, just rearranged differently.
Given an array of strings strs, your task is to group all anagrams together. Each group should contain strings that are anagrams of each other.
For example: ["eat", "tea", "tan", "ate", "nat", "bat"] should be grouped as [["eat","tea","ate"],["tan","nat"],["bat"]] because:
- "eat", "tea", "ate" all contain the same characters: e, a, t
- "tan", "nat" both contain: t, a, n
- "bat" stands alone with: b, a, t
You can return the groups in any order, and the strings within each group can also be in any order.
Input & Output
Visualization
Time & Space Complexity
n strings, each taking O(m log m) to sort where m is average string length
Hash map stores all strings plus sorted keys
Constraints
- 1 ≤ strs.length ≤ 104
- 0 ≤ strs[i].length ≤ 100
- strs[i] consists of lowercase English letters only