From 3e51e5ec49896bd9aa2e4f3aa5085f5ac771b13b Mon Sep 17 00:00:00 2001 From: Katie Date: Tue, 5 Jan 2021 00:46:04 -0800 Subject: [PATCH] implemented methods --- .DS_Store | Bin 0 -> 6148 bytes lib/exercises.rb | 40 ++++++++++++++++++++++++++++++++++------ 2 files changed, 34 insertions(+), 6 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5c3fb944b4bd0afd6cc0030643a2a554f11c781d GIT binary patch literal 6148 zcmeHK%}(Pm5VlKqNvMRf5(khtSmMB?heE668kL_D5{Mu;09z6zqLHEmB`!Twl_DO1 z2Y@R-?*TjnFT$M}+eM(l4Xu{dj5PknYIbe9 zW*>RotnW!*_KLQjcbs`I4x_-&_v27@ccXMYiO!;QE8p~GlpkR5Zk8nwplv_ci=%$W znOV(J>Bni5t9rV|;eMQkS-+k2(y&nRrns`Vec6RN)`ENNDlToy?l`l9L9^Mai)L$i zSQmqpl}25(n!krb+p^{sH+KH?&Mz*nu5WJd?jQ6HaQL$-`DJhfk6^r#apvV|lBFl$ z8^w>}2#En=fEf7Z447lhs(tfy(9b6Zh=H$X0M7>jis%|FHL9Zn8vK03@hTz;*!Y$} z6b4;`rA8P5;W`yir*iYe;5r@r!o;}-ON~06aWym4F*9@XLg8w5@Cy~rxT}#`Vt^QU z&%lK4I(YxDfByb|pF}-kfEf6%7~s`4Z>VfTDpKV&Jbb@B%b-V8j3b literal 0 HcmV?d00001 diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..41bcd60 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,19 +1,47 @@ # 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 * m) where m is the num words and n is longest num of characters in the words +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.empty? + hash_of_letter_groups_and_words = {} + strings.each do |word| + sorted_word = word.chars.sort + if hash_of_letter_groups_and_words.keys.include?(sorted_word) + hash_of_letter_groups_and_words[sorted_word].push(word) + else + hash_of_letter_groups_and_words[sorted_word] = [word] + end + end + return hash_of_letter_groups_and_words.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 log n) +# Space Complexity: O (n) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if list.empty? + hash_occurences = {} + list.each do |num| + if hash_occurences.keys.include?(num) + hash_occurences[num] += 1 + else + hash_occurences[num] = 1 + end + end + + sorted_array = hash_occurences.sort_by{|k,v| -v} + + k_most_frequent_elements = [] + + k.times do |i| + k_most_frequent_elements.push(sorted_array[i][0]) + end + + return k_most_frequent_elements end