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
39 changes: 31 additions & 8 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,43 @@


# 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) where n is the number of elements in the array

Choose a reason for hiding this comment

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

Assuming the words are small, yes.

# Space Complexity: O(n)

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

hash = {}
strings.each do |word|
sorted_word = word.split("").sort
if hash[sorted_word]
hash[sorted_word] << word
end
end
final_anagrams = []
hash.each do |k, v|
anagrams << v
end
return final_anagrams
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!"
hash = {}

list.each do |value|
if hash[value]
hash[value] += 1
else
hash[value] = 1
end
end

top_elements = Array.new(k)
return top_elements = hash.sort_by{ |key, value| value }

Choose a reason for hiding this comment

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

You just need to limit the return to the 1st k elements, but otherwise you have it.

end


Expand Down