diff --git a/lib/exercises.rb b/lib/exercises.rb index e1b3850..403060a 100644 --- a/lib/exercises.rb +++ b/lib/exercises.rb @@ -1,19 +1,49 @@ # 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!" + # raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if strings.empty? + + hash = Hash.new + + strings.each do |word| + array_letters = word.split("").sort + + if hash[array_letters] + hash[array_letters] << word + else + hash[array_letters] = [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(nlogn) +# Space Complexity: O(n) def top_k_frequent_elements(list, k) - raise NotImplementedError, "Method hasn't been implemented yet!" + # raise NotImplementedError, "Method hasn't been implemented yet!" + return [] if list.empty? + + hash = Hash.new(0) + + list.each do |num| + hash[num] += 1 + end + + sorted_hash = hash.sort_by {|key, value| -value} + + return sorted_hash[0..k-1].map { |num, count| num} + + end