Fast, super-simple Ruby solution


  • 0
    Y
    def group_anagrams(arr)
      anagrams = Hash.new # hash with key of sorted characters
      arr.length.times do |i|
        str = arr[i]
        str = str.chars.sort.join("") # sort chars, so bca => abc
    
        if anagrams.include? str
          anagrams[str] << arr[i] # append to group
        else
          anagrams[str] = [arr[i]] # create new group
        end
      end
      anagrams.each_with_object([]) {|(k, v), obj| obj << [v].flatten }
    end
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.