From 970a67ce6939147d231643494d86de466dd3f028 Mon Sep 17 00:00:00 2001 From: Anya Tokar Date: Sat, 1 May 2021 18:15:24 -0700 Subject: [PATCH 1/2] grouped_anagrams --- lib/exercises.rb | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..84011a6 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,11 +1,16 @@ # 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) n is the length of the array, m is the max length of string within the array +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.empty? + hash_map = Hash.new([]) + strings.each do |string| + hash_map[string.chars.sort] += [string] + end + return hash_map.map {|k, v| v} end # This method will return the k most common elements From 710178d936e998b3b1afe8220f86a24337affd26 Mon Sep 17 00:00:00 2001 From: Anya Tokar Date: Sat, 8 May 2021 18:45:39 -0700 Subject: [PATCH 2/2] top k function --- lib/exercises.rb | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 84011a6..4e962f2 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,24 +1,41 @@ # This method will return an array of arrays. # Each subarray will have strings which are anagrams of each other -# Time Complexity: O(n * m) n is the length of the array, m is the max length of string within the array +# Time Complexity: O(n * m) n is the length of the array, m is the max length of string within the array. +# Could pull chars method to run first on each element of strings, for O(n) n being the longest string or array. # Space Complexity: O(n) def grouped_anagrams(strings) - return [] if strings.empty? - hash_map = Hash.new([]) + return [] if strings.nil? + return [] if strings.empty? + + counts_hash = Hash.new([]) strings.each do |string| - hash_map[string.chars.sort] += [string] + counts_hash[string.chars.sort] += [string] end - return hash_map.map {|k, v| v} + return counts_hash.map {|k, v| v} 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) n is list length +# Space Complexity: O(n^2 * k) is that right? def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if list.nil? + return [] if list.empty? + + counts_hash = Hash.new(0) # space = O(n) + list.each do |num| + counts_hash[num] += 1 + end + + sorted_values_2d = counts_hash.sort_by {|k, v| -v} # space = O(n) + + k_most_common_ele = [] # space = O(k) + k.times do |i| + k_most_common_ele << sorted_values_2d[i][0] + end + return k_most_common_ele end