Skip to content
Open
Show file tree
Hide file tree
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
52 changes: 45 additions & 7 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +5 to +6

Choose a reason for hiding this comment

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

👍


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)

Choose a reason for hiding this comment

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

where n is the number of distinct elements.

You also should consider that the list might be much longer than the number of distinct elements.

So maybe O(n + k log k) where k is the number of distinct elements and n the number of elements.

# 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
Comment on lines +50 to +51

Choose a reason for hiding this comment

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

indentation

end

return return_array

end


Expand All @@ -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
end
2 changes: 1 addition & 1 deletion test/exercises_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down