MediumLeetCode #49Arrays & Hashing
Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
Constraints
1 <= strs.length <= 10^4, 0 <= strs[i].length <= 100
Examples
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Solution Approach
Use HashMap to store element frequencies or mappings. Iterate through array once to build map, then solve based on stored data. Common for two-sum and anagram problems.
Implementation
def twoSum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []Complexity Analysis
Time Complexity
O(n)Space Complexity
O(n)Key Learning Points
HashMap for O(1) lookupsSingle pass solutionComplement/pairing pattern
Related Problems to Practice
Two SumValid AnagramGroup Anagrams
Complexity
Time:O(n)
Space:O(n)
Hints
- 1.How can you identify anagrams uniquely?
- 2.What if you sort each string?
- 3.Use a hash map with sorted string as key
Asked at
Google