Group Anagrams

Groups words that are anagrams of each other.

Medium

Examples

Example 1: ["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]]

Implementation

Ruby

  # 🔤 3. Group Anagrams
  # Groups words that are anagrams of each other.
  # Sorts the characters in each word and uses that sorted string as the hash key.
  # Time Complexity: O(n * k log k)
  # Where:
  # n = number of strings
  # k = average length of a string
  # Why: Each word is sorted (which takes O(k log k)), and we do that for each of the n words.
  def group_anagrams(strs)
    groups = Hash.new { |h, k| h[k] = [] }
    strs.each do |s|
      key = s.chars.sort.join
      groups[key] << s
    end
    groups.values

Complexity Analysis

Time Complexity: O(n * k log k)
Space Complexity: O(n * k)

Patterns & Techniques

Problem Details

Category: Array Hashing Examples
Difficulty: Medium
Module: ArrayHashingExamples
Method: group_anagrams
← Back to Array Hashing Examples