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.

Input & Output

Example 1 — Basic Anagram Grouping
$ Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
💡 Note: eat, tea, ate contain same letters (a,e,t). tan, nat contain same letters (a,n,t). bat stands alone with letters (a,b,t).
Example 2 — Empty String
$ Input: strs = [""]
Output: [[""]]
💡 Note: Single empty string forms one group by itself.
Example 3 — Single Character
$ Input: strs = ["a"]
Output: [["a"]]
💡 Note: Single string with one character forms one group.

Constraints

  • 1 ≤ strs.length ≤ 104
  • 0 ≤ strs[i].length ≤ 100
  • strs[i] consists of lowercase English letters only

Visualization

Tap to expand
Group Anagrams - Hash Approach INPUT String Array: strs[] "eat" "tea" "tan" "ate" "nat" "bat" Sort each word: "eat" --> "aet" "tea" --> "aet" "tan" --> "ant" "ate" --> "aet" "nat" --> "ant" "bat" --> "abt" ALGORITHM STEPS 1 Create HashMap key: sorted string value: list of anagrams 2 For each word Sort chars to get key 3 Add to HashMap Group by sorted key 4 Return values All grouped lists HashMap Structure "aet" --> [eat,tea,ate] "ant" --> [tan,nat] "abt" --> [bat] FINAL RESULT Grouped Anagrams: Group 1 (key: "aet") ate eat tea Group 2 (key: "ant") nat tan Group 3 (key: "abt") bat Output: [[bat], [nat,tan], [ate,eat,tea]] Key Insight: Anagrams have the same characters, so when sorted alphabetically, they produce identical strings. Use the sorted string as a hash key to group all anagrams together in O(n * k log k) time, where n = number of strings and k = max string length. TutorialsPoint - Group Anagrams | Hash Approach
Asked in
Amazon 85 Facebook 72 Microsoft 68 Google 54
270.6K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen