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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit