Skip to content
LEETFLIX

Medium · group by sorted key. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 49. Group Anagrams. The copyrighted prompt is on LeetCode. This page is a working group by sorted key for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

strs =
eat tea tan ate nat bat

Output

[[eat, tea, ate], [tan, nat], [bat]]

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Sort each word as the map key

Anagrams share a sorted signature. Bucket words by sorted(word).

eat, tea, ate all sort to aet. One hash map from signature → list is the whole algorithm.

Algorithm

  1. For each word, sort its letters to get a key.
  2. Append the word to that key's bucket.
  3. Return the buckets.
Time
O(n k log k)
Space
O(n k)
Solution.py
class Solution:    def groupAnagrams(self, words: list[str]) -> list[list[str]]:        groups: dict[str, list[str]] = {}        for w in words:            key = "".join(sorted(w))            groups.setdefault(key, []).append(w)        return list(groups.values())
Watch this run

03

Interactive walkthrough

Playing “Sort each word as the map key”. Edit the input, hit Run, then scrub.

Approach: Sort each word as the map key

Loading animation…