Back

Group Anagrams

medium

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Test Cases

Copy an input into the main harness and Run to verify
Input
strs = ["eat","tea","tan","ate","nat","bat"]
Expected Output
[["bat"],["nat","tan"],["ate","eat","tea"]]
Input
strs = [""]
Expected Output
[[""]]
Input
strs = ["a"]
Expected Output
[["a"]]

Constraints

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

Hints

Hint 1 — click to reveal

Anagrams share the same sorted character sequence — use it as a hash key.

Hint 2 — click to reveal

Alternatively, encode the 26 character counts as the key.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.