From 9160649caaedac65b917c768b2b6f3ed6426bab9 Mon Sep 17 00:00:00 2001 From: Leah Date: Mon, 14 Sep 2020 10:53:05 -0700 Subject: [PATCH 1/2] methods passing tests --- lib/exercises.rb | 49 ++++++++++++++++++++++++++++++++++++------ test/exercises_test.rb | 1 + 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..7aaa9d7 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,19 +1,54 @@ # 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) - n is number of words in the array +# Space Complexity: O(n) - n is number of words in the array def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.empty? + + hash = {} + + strings.each do |word| + sorted_word = word.chars.sort.join + if hash[sorted_word] + hash[sorted_word] << word + else + hash[sorted_word] = [] + hash[sorted_word] << word + end + end + + return hash.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) - n is length of list +# Space Complexity: O(n) - n is the length of the list def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if list.empty? + return list if list.size == 1 + return [list[0]] if k == 1 + + hash = {} + list.each do |num| + if hash[num] + hash[num] += 1 + else + hash[num] = 1 + end + end + + sorted_nums = hash.sort_by{|num,count| count}.reverse + + most_freq = [] + i = 0 + k.times do + most_freq << sorted_nums[i][0] + i+=1 + end + + return most_freq end diff --git a/test/exercises_test.rb b/test/exercises_test.rb index dd93104..b8e2e96 100644 --- a/test/exercises_test.rb +++ b/test/exercises_test.rb @@ -76,6 +76,7 @@ # Act answer = top_k_frequent_elements(list, k) + puts "ANSWER: #{answer}" # Assert expect(answer.sort).must_equal [1,2] From 6dc917434d51696f4a0b507ca87740c6d04a0597 Mon Sep 17 00:00:00 2001 From: Leah Date: Mon, 14 Sep 2020 10:54:47 -0700 Subject: [PATCH 2/2] take out test frag --- test/exercises_test.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/test/exercises_test.rb b/test/exercises_test.rb index b8e2e96..dd93104 100644 --- a/test/exercises_test.rb +++ b/test/exercises_test.rb @@ -76,7 +76,6 @@ # Act answer = top_k_frequent_elements(list, k) - puts "ANSWER: #{answer}" # Assert expect(answer.sort).must_equal [1,2]