MEDIUM NC#4 Blind #54 Arrays & Hashing
49. Group Anagrams
๐ Problem
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, typically using all the original letters exactly once.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Anagrams have same sorted string representation
- โ Use sorted string as hash map key
- โ Group all strings with same key together
- โ Time: O(n * k log k) where k is max string length
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขAnagrams have same sorted string representation
- โขUse sorted string as hash map key
- โขGroup all strings with same key together
Common Pitfalls
- โขTime: O(n * k log k) where k is max string length
๐งช Test Cases
Hidden tests on submit: 2
Test Case 1
Not run Input:
groupAnagrams(["eat","tea","tan","ate","nat","bat"]); Expected:
[["eat","tea","ate"], ["tan","nat"], ["bat"]] Test Case 2
Not run Input:
groupAnagrams([""]); Expected:
[[""]] Test Case 3
Not run Input:
groupAnagrams(["a"]); Expected:
[["a"]] ๐ Code Editor
๐ค Output