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

# 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: On
# Space Complexity: On

def grouped_anagrams(strings)
Comment on lines +3 to 6

Choose a reason for hiding this comment

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

Clever, I like the use of a subhash as a key.

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

strings.each do |string|
child = {}

string.each_char do |char|
child[char] ? child[char] += 1 : child[char] = 1
end

hash[child] ? hash[child] << string : hash[child] = [string]
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: ?
# Time Complexity: On
# Space Complexity: On
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.

Not quite working as it fails for [3, 3, 3, 3, 3, 1, 1, 2, 2, 2]

raise NotImplementedError, "Method hasn't been implemented yet!"
result = []
list = list.sort.uniq

return list if list.length == k
return result if list.length == 0

i = 0
k.times do
result << list[i]
i += 1
end

return result
end


Expand Down