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
49 changes: 42 additions & 7 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,54 @@

# 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) - n is number of words in the array
# Space Complexity: O(n) - n is number of words in the array
def grouped_anagrams(strings)
Comment on lines +4 to 6

Choose a reason for hiding this comment

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

👍

raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if strings.empty?

hash = {}

strings.each do |word|
sorted_word = word.chars.sort.join
if hash[sorted_word]
hash[sorted_word] << word
else
hash[sorted_word] = []
hash[sorted_word] << 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(n) - n is length of list
# Space Complexity: O(n) - n is the length of the list
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.

👍 , nice work, however you're already sorting the list, which would be O(n log n)

raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if list.empty?
return list if list.size == 1
return [list[0]] if k == 1

hash = {}
list.each do |num|
if hash[num]
hash[num] += 1
else
hash[num] = 1
end
end

sorted_nums = hash.sort_by{|num,count| count}.reverse

most_freq = []
i = 0
k.times do
most_freq << sorted_nums[i][0]
i+=1
end

return most_freq
end


Expand Down