From feb00c47d3421f70d495f0f5870aa5e113344ccf Mon Sep 17 00:00:00 2001 From: Jing <60051579+Jing-321@users.noreply.github.com> Date: Wed, 21 Apr 2021 23:04:30 -0700 Subject: [PATCH] complete --- lib/exercises.rb | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..ebb51c6 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,11 +1,26 @@ # 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!" + words = Hash.new + + strings.each do |string| + letter_count = Hash.new + string.each_char do |c| + letter_count[c] = letter_count[c] ? letter_count[c] + 1 : 1 + end + + if words[letter_count] + words[letter_count].push(string) + else + words[letter_count] = [string] + end + end + + return words.values end # This method will return the k most common elements @@ -13,7 +28,13 @@ def grouped_anagrams(strings) # Time Complexity: ? # Space Complexity: ? def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + element_count = {} + + list.each do |element| + element_count[element] = element_count[element] ? element_count[element] + 1 : 1 + end + + return element_count.max_by(k) {|a| a[1]}.map {|a| a[0]} end