↓Skip to main content
  1. LeetCode/

LeetCode 49: Group Anagrams

·2 mins· ·
LeetCode Medium Array Hash-Table String Sorting
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-22

  • Submissions: Runtime Error → Wrong Answer ×2 → Time Limit Exceeded ×3 → Accepted → Runtime Error → Accepted ×3

Approach
#

Anagrams are identical after sorting, so use "".join(sorted(s)) (or tuple(sorted(s))) as the key (Hash Table Template 5) in a defaultdict(list) and return all values. A 26-length count tuple also works as a key and skips sorting.

My Attempts
#

This took 11 submissions:

  • Attempt 1 had a typo (rse, NameError); attempt 2 only searched existing groups and never created a new one, so it always returned an empty list.
  • Attempt 3 added new groups but used set to match them: ["bb", "b"] landed in one group.
  • Comparing with Counter fixed the answers, but each string was compared with every group, timing out three times.
  • Switching to “sorted string as key” passed. A 2022-10-27 rewrite wrote values instead of values() and raised one more RE.

Solution
#

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)
        for s in strs:
            groups["".join(sorted(s))].append(s)
        return list(groups.values())

Complexity
#

Time O(n · k log k) for string length k, space O(nk).

Mistakes to Avoid
#

  • Sets do not work: "bb" and "b" share a character set but are not anagrams.
  • Comparing each string with every existing group is O(n²) and times out; a key finds the group directly.
  • dict.values is a method and needs parentheses.

Interview Explanation
#

I key a hash map by each string’s sorted form, so anagrams share a key, and return the groups. Time O(n · k log k); for long strings a 26-letter count tuple can be the key instead.

Related

LeetCode 47: Permutations II
·2 mins
LeetCode Medium Array Backtracking Sorting
LeetCode 47 note: sort first, and within a level skip a value equal to the previous one when the previous one is unused
LeetCode 56: Merge Intervals
·2 mins
LeetCode Medium Array Sorting Quicksort
LeetCode 56 note: sort by start; if a new interval starts at or before the last merged end, merge (taking the max end), otherwise open a new one
LeetCode 36: Valid Sudoku
·2 mins
LeetCode Medium Array Hash-Table Matrix
LeetCode 36 note: each digit may appear once per row, column and 3 × 3 box; put (digit, row), (digit, column) and (digit, box) keys into one set
LeetCode 15: 3Sum
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 15 note: sort, fix the first number, and find the other two with converging pointers, skipping equal values at all three positions to avoid duplicate triplets
LeetCode 16: 3Sum Closest
·2 mins
LeetCode Medium Array Two-Pointers Sorting
LeetCode 16 note: sort, fix one number, and find the other two with converging pointers, comparing the distance abs(sum - target)
LeetCode 17: Letter Combinations of a Phone Number
·2 mins
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 note: each level handles one digit and tries its letters; an empty input returns an empty list