From baf706299bdfc87f86c1696e64b485a251ac1814 Mon Sep 17 00:00:00 2001 From: Bitaman Date: Sun, 29 Sep 2019 06:25:51 -0700 Subject: [PATCH] finished and tests are passing --- lib/exercises.rb | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 2cb2bfa..f4289b3 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -2,11 +2,21 @@ # This method will return an array of arrays. # Each subarray will have strings which are anagrams of each other -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n * m log m)we go through the array once and for each string we sort which is an m log m time complexcity +# Space Complexity: O(n) worse case we don't have any anagram and the size of the hash table is the same size of the array def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.length == 0 + word_hash = Hash.new() + strings.each do |string| + element = string.split("").sort.join + if word_hash[element] + word_hash[element] << string + else + word_hash[element] = [string] + end + end + return word_hash.values end # This method will return the k most common elements