From 900df56bcd0e3470a4e207110e922a06c7ebc8be Mon Sep 17 00:00:00 2001 From: Myriam Walden-Duarte Date: Mon, 16 Sep 2019 00:14:52 -0700 Subject: [PATCH 1/2] grouped anagrams - top k frecuent elements --- lib/exercises.rb | 62 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 4 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 2cb2bfa..8b202c4 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -2,11 +2,25 @@ # 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(m*n log n), where m is each of the items on strings and n is the amount of characters on each string +# Space Complexity: O(m*n), where m is each of the items on strings and n is the amount of characters on each string def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + + groups = {} + + strings.each_with_index do |word, index| + key = word.chars.sort + + if groups[key] + groups[key] << word + else + groups[key] = [word] + end + end + + return groups.values + end # This method will return the k most common elements @@ -14,7 +28,47 @@ def grouped_anagrams(strings) # Time Complexity: ? # Space Complexity: ? def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + + if list.empty? + return [] + end + + list_count = {} + + list.each_with_index do |item, index| + if list_count[item] + list_count[item] +=1 + else + list_count[item] = 1 + end + end + + values = list_count.values + keys = list_count.keys + max_value = 0 + count_repeated = 0 + + max_value = values.first + values.each do |value| + if value == max_value + count_repeated += 1 + if count_repeated == list_count.length + keys.sort + return keys.first(k) + end + end + end + + index_values = values.map.with_index.sort.map(&:last) + k_indexes = index_values.last(k) + k_values = [] + + k_indexes.each do |index_to_print| + k_values.push(keys[index_to_print]) + end + + return k_values + end From de2b0b88947a7c5eac768b7b350a74569cf6eb2b Mon Sep 17 00:00:00 2001 From: Myriam Walden-Duarte Date: Mon, 16 Sep 2019 00:30:13 -0700 Subject: [PATCH 2/2] test uncommented --- test/exercises_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/exercises_test.rb b/test/exercises_test.rb index a649110..dd93104 100644 --- a/test/exercises_test.rb +++ b/test/exercises_test.rb @@ -68,7 +68,7 @@ end end - xdescribe "top_k_frequent_elements" do + describe "top_k_frequent_elements" do it "works with example 1" do # Arrange list = [1,1,1,2,2,3]