From a614a1f3d06fa0ed505f6fa373b80234896e9f3a Mon Sep 17 00:00:00 2001 From: "yesenia.torres3" Date: Wed, 30 Sep 2020 14:43:12 -0700 Subject: [PATCH] passing tests --- lib/exercises.rb | 60 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..93bf2a5 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,19 +1,67 @@ # 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 |word| + letter_grouping = word.split('').sort().join() + + if !hash[letter_grouping] + hash[letter_grouping] = [] + end + + hash[letter_grouping] << word + end + + return hash.values 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!" + return [] if list.empty? + + counts_hash = {} + + list.each do |number| + if !counts_hash[number] + counts_hash[number] = 1 + else + counts_hash[number] = counts_hash[number] + 1 + end + end + + length_to_num_hash = {} + + counts_hash.keys.each do |number| + if !length_to_num_hash[counts_hash[number]] + length_to_num_hash[counts_hash[number]] = [] + end + length_to_num_hash[counts_hash[number]] << number + end + + result_length = k + result = [] + most_freq_num = length_to_num_hash.keys.max + + while result_length > 0 && most_freq_num != nil && most_freq_num >= 0 + if length_to_num_hash[most_freq_num] + length_to_num_hash[most_freq_num].each do |num| + result << num + result_length -= 1 + break if result_length <= 0 + end + end + most_freq_num -= 1 + end + + return result end