From 3ceb67a676df02b8e584499c1acb7a00b6c051b9 Mon Sep 17 00:00:00 2001 From: Alice D Date: Sun, 16 May 2021 21:10:11 -0500 Subject: [PATCH 1/2] grouped_anagrams --- lib/exercises.rb | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..d440962 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,11 +1,27 @@ # 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!" + anagrams_hash = Hash.new + + strings.each do |string| + alphabetically_sorted_string = string.chars.sort + if anagrams_hash[alphabetically_sorted_string] + anagrams_hash[alphabetically_sorted_string] << string + else + anagrams_hash[alphabetically_sorted_string]=[string] + end + end + + output_array = [] + anagrams_hash.each do |key,value| + output_array << value + end + + return output_array end # This method will return the k most common elements From 9f0687a5934333db85e3898298d05ee7b2adc6da Mon Sep 17 00:00:00 2001 From: Alice D Date: Sun, 16 May 2021 21:44:39 -0500 Subject: [PATCH 2/2] top_k_frequenct_elements --- lib/exercises.rb | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index d440962..a5bdb14 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -26,12 +26,31 @@ 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^2) because of the .sort_by used mid method +# Space Complexity: O(n) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" -end + return [] if list.nil? || list == [] + + frequency_hash = Hash.new + + list.each do |integer| + if frequency_hash[integer] + frequency_hash[integer] += 1 + else + frequency_hash[integer] = 1 + end + end + + descending_freq_array = frequency_hash.sort_by {|k,v| -v} + i = 0 + output_array = [] + until i == k do + output_array << descending_freq_array[i][0] + i += 1 + end + return output_array +end # This method will return the true if the table is still # a valid sudoku table.