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

# 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(m + n + nlog(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.

👍 I would say this is n * m log m where n is the number of strings and m is the length of the strings. Or if the strings are all less than a certain size, O(n) for time complexity.

Otherwise well done.

raise NotImplementedError, "Method hasn't been implemented yet!"
grouped = {}
strings.each do |e|
current_sorted = e.split("").sort.join("")
if !grouped["#{current_sorted}"]
grouped["#{current_sorted}"] = [e]
else
grouped["#{current_sorted}"] << e
end
end
return grouped.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 log(n))
# Space Complexity: O(n)
def top_k_frequent_elements(list, k)
Comment on lines +22 to 24

Choose a reason for hiding this comment

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

👍 , is there a way to do this in O(nk) time?

raise NotImplementedError, "Method hasn't been implemented yet!"
if list.length == 0
return []
end
nums = {}
list.each do |num|
if !nums[num]
nums[num] = 1
else
nums[num] += 1
end
end

sorted = nums.sort_by {|k, v| -v}
top_k = []
k.times do |k|
top_k << sorted[k][0]
end
return top_k
end


Expand All @@ -27,3 +53,7 @@ def top_k_frequent_elements(list, k)
def valid_sudoku(table)
raise NotImplementedError, "Method hasn't been implemented yet!"
end



#if col + 1 % 3 == 0 && row + 1 % 3 == 0 -> check square