MediumHash TableStringSorting

Group Anagrams

LeetCode
2 approaches, code in all languages

You are given a list of lowercase words. Two words belong together when one can be produced by shuffling the letters of the other, using every letter exactly as many times. Your job is to partition the list into buckets so that each bucket holds precisely the words that are rearrangements of one another.

Return the collection of buckets. The buckets may appear in any order, and the words inside a single bucket may also be listed in any order.

Example 1

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

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

"eat", "tea", and "ate" share the same letters, so they land in one bucket. "tan" and "nat" form another, and "bat" stands alone.

Example 2

Input: strs = ["abc","bca","xyz"]

Output: [["abc","bca"],["xyz"]]

"abc" and "bca" are rearrangements of each other; "xyz" matches nothing else.

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] contains only lowercase English letters
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now