Groups words that are anagrams of each other.
["eat","tea","tan","ate","nat","bat"] → [["eat","tea","ate"],["tan","nat"],["bat"]]
# 🔤 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
O(n * k log k)
O(n * k)