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
38 changes: 32 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(n)
# Space Complexity: o(n)

def grouped_anagrams(strings)
raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if strings.length == 0

anagrams = Hash.new([])
strings.each do |element|
sorted_letters = element.sort
if anagrams[sorted_letters]
anagrams[sorted_letters] << element
else
anagrams[sorted_letters] = element
end
end
return anagrams.values
# strings.each.with_index { |el, i| anagrams[el.downcase.chars.sort.join] += [i] }
# anagrams.map { |key, indexes| indexes.map { |i| strings[i] } }
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)
# Space Complexity: o(n)
def top_k_frequent_elements(list, k)
raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if list.length == 0
hash_list = {}

list.each do |number|
if hash_list[number]
hash_list[number] += 1
else
hash_list[number] = 1
end
end

sortedhash = Hash[hash_list.sort_by { |key, value| -value }[0...k]]

return sortedhash.keys
end


Expand Down