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,21 +1,56 @@

# 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.

👍 Nice work, just a note if the strings are limited in size, the time complexity is O(n), otherwise it is O(n * m log m) where n is the number of strings and m is the length of the strings.

raise NotImplementedError, "Method hasn't been implemented yet!"
anagrams_hash = Hash.new

strings.each do |string|
alphabetically_sorted_string = string.chars.sort
if anagrams_hash[alphabetically_sorted_string]
anagrams_hash[alphabetically_sorted_string] << string
else
anagrams_hash[alphabetically_sorted_string]=[string]
end
end

output_array = []
anagrams_hash.each do |key,value|
output_array << value
end

return output_array
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^2) because of the .sort_by used mid method
# Space Complexity: O(n)
def top_k_frequent_elements(list, k)
Comment on lines +29 to 31

Choose a reason for hiding this comment

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

👍 Because you're sorting the (and not in a loop) your algorithm is O(n log n) because Ruby uses MergeSort internally.

raise NotImplementedError, "Method hasn't been implemented yet!"
end
return [] if list.nil? || list == []

frequency_hash = Hash.new

list.each do |integer|
if frequency_hash[integer]
frequency_hash[integer] += 1
else
frequency_hash[integer] = 1
end
end

descending_freq_array = frequency_hash.sort_by {|k,v| -v}

i = 0
output_array = []
until i == k do
output_array << descending_freq_array[i][0]
i += 1
end
return output_array
end

# This method will return the true if the table is still
# a valid sudoku table.
Expand Down