diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..9ac52d0 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) +# Space Complexity: O(n) def grouped_anagrams(strings) - raise NotImplementedError, "Method hasn't been implemented yet!" + hash = {} + + strings.each do |str| + + anagram_key = str.chars.sort + + if hash[anagram_key] + hash[anagram_key] << str + else + hash[anagram_key] = [str] + 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: O(n) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + hash = Hash.new(0) + k_array = [] + + return [] if list.empty? + + list.each do |num| + hash[num] += 1 + end + + descending_hash = hash.sort_by {|key, value| -value} + + k.times do |i| + k_array << descending_hash[i][0] + end + + return k_array end