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

# 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: 0(1)
# Space Complexity: 0(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.

👍 , however your time complexity is off. You loop through all the strings so it's a minimum of O(n). If you assume the strings are all small then the sorting can be ignored.

raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if strings.empty?
return [strings] if strings.size == 1

hash1 = {}

# this is the original str
strings.each do |str|

# this is the sorted str
word = str.split("").sort.join("")

# check hash for word
# if not exist, set str as hash value
if hash1[word].nil?
hash1[word] = [str]
else
# or shovel str as hash value
hash1[word] << str
end

end
return hash1.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: 0(1)
# Space Complexity: 0(n)

def top_k_frequent_elements(list, k)
raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if list.empty?

hash1 = {}

list.each do |element|
if hash1[element]
hash1[element] += 1
else
hash1[element] = 1
end
end
sorted = hash1.sort_by {|key, value| -value }
result = []
k.times do |index|
result << sorted[index][0]
end
return result
end


Expand Down