Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Group Anagrams

LeetCode #49Medium
Bucket words by their sorted-letter signature

Given an array of strings, group together the ones that are anagrams of each other (use every word exactly once). Return the groups in any order.

Asked atAmazonUberFacebook
step 1 / 27
eat
tea
tan
ate
nat
bat
[0][1][2][3][4][5]
Brute force · pairwise
1given words
2for i ← 0 to n − 1 (if word i not yet grouped):
3 start group with words[i]
4 for ji + 1 to n − 1:
5 if sorted(words[i]) == sorted(words[j]): add words[j]
6return all groups
state
  • n6

line 1Group words that are anagrams of each other. Two words are anagrams when sorting their letters gives the same string — so we can test any pair by comparing sorted(a) with sorted(b).