From 4571a35708b6e705ce7ca14e8295afff6fb4482e Mon Sep 17 00:00:00 2001 From: Alice Boone Date: Thu, 6 May 2021 15:37:08 -0700 Subject: [PATCH 1/3] Add anagrams --- lib/exercises.rb | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..6a662b6 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,11 +1,24 @@ # 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) +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + hash = {} + + strings.each do |str| + + anagram_key = str.chars.sort + + if hash[anagram_key] + hash[anagram_key] << str + else + hash[a_key] = [str] + end + end + + return hash.values end # This method will return the k most common elements From d77b4ec13d04956e0dbe84918a9bc3113be97414 Mon Sep 17 00:00:00 2001 From: Alice Boone Date: Thu, 6 May 2021 15:39:06 -0700 Subject: [PATCH 2/3] Add top_k --- lib/exercises.rb | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 6a662b6..aaf5468 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -23,10 +23,25 @@ def grouped_anagrams(strings) # 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 = Hash.new(0) + k_array = [] + + return [] if list.empty? + + list.each do |num| + hash[num] += 1 + end + + descending_hash = hash.sort_by {|key, value| -value} + + k.times do |i| + k_array << descending_hash[i][0] + end + + return k_array end From 07350f07e292f6d0b05544f54760def7b3681ea6 Mon Sep 17 00:00:00 2001 From: Alice Boone Date: Thu, 6 May 2021 15:44:11 -0700 Subject: [PATCH 3/3] fixing typo --- lib/exercises.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index aaf5468..9ac52d0 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -14,7 +14,7 @@ def grouped_anagrams(strings) if hash[anagram_key] hash[anagram_key] << str else - hash[a_key] = [str] + hash[anagram_key] = [str] end end