From ee6fba85bff88bed85cce285c195dec7effc3991 Mon Sep 17 00:00:00 2001 From: dnguye2 Date: Fri, 11 Sep 2020 22:25:09 -0700 Subject: [PATCH 1/2] completed grouped_anagrams method --- lib/exercises.rb | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..16a5f3d 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -5,7 +5,20 @@ # Space Complexity: ? def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + string_hashmap = {} + strings.each do |string| + if string_hashmap[grouped_anagrams_helper(string)] + string_hashmap[grouped_anagrams_helper(string)] << string + else + string_hashmap[grouped_anagrams_helper(string)] = [] + string_hashmap[grouped_anagrams_helper(string)] << string + end + end + return string_hashmap.values +end + +def grouped_anagrams_helper(string) + return string.chars.sort.join end # This method will return the k most common elements From 5a4db0a27b39c7a59cdc0661170d5a8e8ccd14e2 Mon Sep 17 00:00:00 2001 From: dnguye2 Date: Mon, 14 Sep 2020 20:33:42 -0700 Subject: [PATCH 2/2] completed method but not with good time complexity --- lib/exercises.rb | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index 16a5f3d..eb9ce32 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,8 +1,8 @@ # 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(1) def grouped_anagrams(strings) string_hashmap = {} @@ -23,10 +23,30 @@ def grouped_anagrams_helper(string) # 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) in worst case because of the sorting to be done +# Space Complexity: O(1) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + # build hashmap + num_hash = {} + list.each do |num| + if num_hash[num] + num_hash[num] += 1 + else + num_hash[num] = 1 + end + end + + # convert hashmap to array + array_num_hash = num_hash.to_a + + # sort by occurences + sorted_array_num_hash = array_num_hash.sort_by {|num| -num[1]} + + # sorted elements only + sorted_numbers = sorted_array_num_hash.map{|num| num[0]} + + # slice sorted array by k elements + return sorted_numbers.slice(0, k) end