TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1432 359
🎯 CODING CHALLENGE #12 - Group Anagrams
Difficulty: Medium | Asked at: Amazon, Meta, Uber

Given an array of strings, group the anagrams together.


Input: ["eat","tea","tan","ate","nat","bat"]
Output: [["eat","tea","ate"],["tan","nat"],["bat"]]


💡 Hint: Two words are anagrams if and only if their sorted characters are identical. That sorted string makes a perfect hash key.

Solution:
python
from collections import defaultdict

def group_anagrams(strs):
groups = defaultdict(list)
for s in strs:
key = ''.join(sorted(s))
groups[key].append(s)
return list(groups.values())


Complexity: O(n · k log k) time, where n is the number of strings and k is the max string length - sorting each string dominates. Space O(n · k).

Common mistake: Trying to compare every pair of strings directly (O(n²) comparisons) instead of using a canonical key to bucket them in one pass. Any time you see "group things that share a property," ask: "what's the key I can compute once per item?"

Bonus optimization: instead of sorting (O(k log k)), you can build a character-count tuple as the key in O(k) time - faster for long strings. Worth mentioning if you want to show extra depth.

Sorted-string-as-key or character-count-as-key - which would you reach for first? 👇
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →