From df987d59ca8c751c3d25d0bfa9ef81f3c05b4186 Mon Sep 17 00:00:00 2001 From: Sharon Cheung Date: Mon, 14 Sep 2020 22:00:26 -0700 Subject: [PATCH] tests passed --- lib/exercises.rb | 43 ++++++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..2cde640 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,21 +1,50 @@ # 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(n2) +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.length == 0 + result = {} + strings.each do |word| + char = word.chars.sort.join + result[char] ||= [] + result[char] << word + end + return result.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!" -end + return [] if list.length == 0 + frequency = {} + # number as key + # frequency as value + + list.each do |num| + if frequency[num].nil? + frequency[num] = 1 + else + frequency[num] += 1 + end + end + result = [] + + frequency.keys.each do |num| + if result.length < k + result << num + else + return result + end + end + + return result +end # This method will return the true if the table is still # a valid sudoku table.