DSA Problems/πŸ“ŠArrays & Hashing

Group Anagrams

ArrayHash TableStringSorting

Problem Statement

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

An anagram is a word formed by rearranging the letters of another word.

Approach

Use sorted string as key in hash map. All anagrams will have the same sorted form.

Complexity Analysis

MetricValue
TimeO(n * k log k) where k is max string length
SpaceO(n * k)

Examples

Example 1

Input: strs = ["eat","tea","tan","ate","nat","bat"] Output: [["bat"],["nat","tan"],["ate","eat","tea"]] Explanation: Anagrams are grouped together

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
Loading...
Sign in to run your code...

Asked by companies:

AmazonFacebookMicrosoftApple