diff --git a/lib/exercises.rb b/lib/exercises.rb index 2cb2bfa..ad9094a 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -2,19 +2,57 @@ # 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) it must go through the entire list +# Space Complexity: O(n) we return an array of size n same as the input array def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + string_hash = {} + + return [] if strings.empty? + + # loop through array, + strings.each do |word| + sorted_word = word.chars.sort.join + if string_hash[sorted_word] + string_hash[sorted_word].push(word) + else + string_hash[sorted_word] = [word] + end + end + + return string_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(nLogn) +# Space Complexity: O(n) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + element_counts = {} + count = 0 + + return list if list.empty? + + list.each do |num| + if element_counts[num] + element_counts[num] += 1 + else + element_counts[num] = 1 + end + + end + + sorted_hash_array = element_counts.sort_by{ |key, val| -val} + + puts sorted_hash_array.to_s + return_array = [] + k.times do |i| + return_array.push(sorted_hash_array[i][0]) + i += 1 + end + + return return_array + end @@ -27,4 +65,4 @@ def top_k_frequent_elements(list, k) # Space Complexity: ? def valid_sudoku(table) raise NotImplementedError, "Method hasn't been implemented yet!" -end \ No newline at end of file +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]