Applied AI Engineer (LLM) coding learning path Level 2 This level · 1 of 31

Group Anagrams

Medium Array Hash Table

Problem

Given a list of words, return the words grouped so that each group holds words that are anagrams of each other. Any group order is accepted.

Original: LeetCode 49: Group Anagrams.

Examples

Example 1

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

Any order of groups, and of words inside a group, is accepted.

Example 2

Input`strs = [""]`
Output`[[""]]`

Example 3

Input`strs = ["a"]`
Output`[["a"]]`

Constraints

  • 1 <= strs.length <= 10^4
  • 0 <= strs[i].length <= 100
  • strs[i] consists of lowercase English letters.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (3)
  1. LeetCode 49: Group Anagramsleetcode.com
  2. Java SE 17 API: Map.computeIfAbsentdocs.oracle.com
  3. [Java SE 17 API: Arrays.sort(char[])](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#sort(char%5B%5D))
Previous
Next