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
41 changes: 37 additions & 4 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,52 @@

# 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: a lot
# 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.

Time complexity 🤣

It's actually O(n) assuming the words are reasonably short O(n * mlog m) otherwise.

raise NotImplementedError, "Method hasn't been implemented yet!"
hash = {}

strings.each do | string |

a_key = string.chars.sort

if hash[a_key]
hash[a_key] << string
else
hash[a_key] = [string]
end
end

return 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: ?
# resource: https://stackoverflow.com/questions/4264133/descending-sort-by-value-of-a-hash-in-ruby
def top_k_frequent_elements(list, k)
Comment on lines 26 to 29

Choose a reason for hiding this comment

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

Good that you cited your source. Time & space complexity?

raise NotImplementedError, "Method hasn't been implemented yet!"
# Hash.new(0) sets default value for any key to 0, while {} sets nil
hash = Hash.new(0)
k_array = []

return [] if list.empty?

# populate the hash and count occurrence
list.each do |num|
hash[num] += 1
end

# set hash's values in descending order
descending_hash = hash.sort_by {|key, value| -value}

# populate the array with most common elements dictated by k
k.times do |i|
k_array << descending_hash[i][0]
end

return k_array
end


Expand Down