From 9f60104471140590998f88ee18bbf38d59f3cd08 Mon Sep 17 00:00:00 2001 From: Amy Phung Date: Sun, 15 Sep 2019 10:44:32 -0700 Subject: [PATCH 1/2] initial --- lib/exercises.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 2cb2bfa..54f6c89 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,4 +1,4 @@ - +# added stufffffff # This method will return an array of arrays. # Each subarray will have strings which are anagrams of each other From c1bd9edea384e833cfcf658b71938b1bb6c464fe Mon Sep 17 00:00:00 2001 From: Amy Phung Date: Sun, 15 Sep 2019 13:59:45 -0700 Subject: [PATCH 2/2] complete exercises --- lib/exercises.rb | 39 +++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 54f6c89..2ffecea 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,20 +1,43 @@ -# added stufffffff - # 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) where n is the number of elements in the array +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.length == 0 + + hash = {} + strings.each do |word| + sorted_word = word.split("").sort + if hash[sorted_word] + hash[sorted_word] << word + end + end + final_anagrams = [] + hash.each do |k, v| + anagrams << v + end + return final_anagrams end # This method will return the k most common elements # in the case of a tie it will select the first occuring element. -# Time Complexity: ? -# Space Complexity: ? +# Time Complexity: O(n) +# Space Complexity: O(n) + def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + hash = {} + + list.each do |value| + if hash[value] + hash[value] += 1 + else + hash[value] = 1 + end + end + + top_elements = Array.new(k) + return top_elements = hash.sort_by{ |key, value| value } end