diff --git a/lib/exercises.rb b/lib/exercises.rb index 2cb2bfa..49b985e 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -2,19 +2,46 @@ # 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!" + return [] if strings.empty? + hash = {} + strings.each do |string| + sorted_string = string.split("").sort.join + if hash[sorted_string] + hash[sorted_string] << string + else + hash[sorted_string] = [string] + 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) +# Space Complexity: 0(n) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + hash = {} + frequent_elements =[] + return [] if k == 0 || list.empty? + + list.each do |element| + if hash[element] + hash[element] += 1 + else + hash[element] = 1 + end + end + sorted_arrays = hash.sort + + k.times do |i| + frequent_elements << sorted_arrays[i][0] + end + + return frequent_elements end diff --git a/test/exercises_test.rb b/test/exercises_test.rb index a649110..dd93104 100644 --- a/test/exercises_test.rb +++ b/test/exercises_test.rb @@ -68,7 +68,7 @@ end end - xdescribe "top_k_frequent_elements" do + describe "top_k_frequent_elements" do it "works with example 1" do # Arrange list = [1,1,1,2,2,3]