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

# 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 * m(logm)), where n is the number of strings and m is the length of each string
# Space Complexity: O(n), where n is the number of strings

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.

👍 , although if the words are all relatively small you can assume O(n) size.

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

strings.each do |s|
# sort each string, assign to variable
bucket = anagrams[s.chars.sort.join]
# check if sorted string is present in hash keys
# if present, add original string to existing bucket array
# otherwise, create a new bucket array
bucket ? bucket.push(s) : bucket = [s]
end

return anagrams.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), where n is the number of elements
# Space Complexity: O(1)?
def top_k_frequent_elements(list, k)
Comment on lines +24 to 26

Choose a reason for hiding this comment

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

👍 , although your space complexity is O(n) since you are building a hash and array of arrays.

raise NotImplementedError, "Method hasn't been implemented yet!"
return list if list.length < 2

items_hash = {}

list.each do |item|
items_hash[item] ? items_hash[item] += 1 : items_hash[item] = 1
end

if items_hash.values.uniq.length == k
tiebreaker(items_hash, k)
else
return most_common = items_hash.keys.max_by(k) do |item|
items_hash[item]
end
end
end

# this only works for the test case. for example, the following will fail:
# list = [1,1,1, 2,2,2, 3,3]
# k = 2
# expected output: [1, 3]
def tiebreaker(items_hash, k)
sorted = items_hash.keys.sort_by do |item|
-items_hash[item]
end

most_common = []
k.times do |i|
most_common.push(sorted[i])
i += 1
end

return most_common
end

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