Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 34 additions & 6 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -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)
Comment on lines +4 to 7

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 The time complexity is O(n) if the strings are limited in size, if they're not because you're sorting the time complexity is O(m * n log n), where m is the number of strings and n is the length of the 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)
Comment on lines +26 to 28

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 However, because you're sorting the time complexity is O(n log n)

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


Expand Down