Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Example 1:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
"bat"."nat" and "tan" are anagrams as they can be rearranged to form each other."ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.Example 2:
Input: strs = [""]
Output: [[""]]
Example 3:
Input: strs = ["a"]
Output: [["a"]]
Constraints:
1 <= strs.length <= 1040 <= strs[i].length <= 100strs[i] consists of lowercase English letters.Why this is a Hash Map problem
Hash maps provide O(1) average-case insert, delete, and lookup. They're used to count frequencies, track what you've seen, map elements to their indices, or group elements by a key. The classic use: convert an O(n²) nested-loop solution to O(n) by pre-processing with a hash map.
What do you want to look up in O(1)? Store that as the key. What information do you need about it? Store that as the value.
For "Two Sum": brute force checks all pairs O(n²). With a hash map, as you scan left-to-right, you store each element and its index. For each new element X, check if (target - X) is already in the map. One pass, O(n). The map makes "have I seen this before?" a O(1) question.
From brute force to optimal — understand every step of the journey
The hash map converts "search" operations from O(n) to O(1). The pattern is: "for each element, I need to quickly look up whether some related value exists" — store that related value as the key when you first encounter it. The one-pass trick works because: if a valid pair (a, b) exists, when you process b, a is already in the map (since a comes before b).