Skip to content
Open

Nara #14

Show file tree
Hide file tree
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: 33 additions & 6 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,46 @@

# 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)

Choose a reason for hiding this comment

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

If the words are expected to be small, this is true.

# Space Complexity: O(n)

def grouped_anagrams(strings)
raise NotImplementedError, "Method hasn't been implemented yet!"
return [] if strings.empty?
hash = {}
strings.each do |string|
sorted_string = string.split("").sort.join
if hash[sorted_string]
hash[sorted_string] << string
else
hash[sorted_string] = [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: ?
# Time Complexity: O(n)

Choose a reason for hiding this comment

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

Look a bit down, you're doing a sort... how is that impacting things?

# Space Complexity: 0(n)

Choose a reason for hiding this comment

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

Zero of n? 0(n)

def top_k_frequent_elements(list, k)
raise NotImplementedError, "Method hasn't been implemented yet!"
hash = {}
frequent_elements =[]
return [] if k == 0 || list.empty?

list.each do |element|
if hash[element]
hash[element] += 1
else
hash[element] = 1
end
end
sorted_arrays = hash.sort

Choose a reason for hiding this comment

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

You're doing a sort here, how does this impact time complexity?


k.times do |i|
frequent_elements << sorted_arrays[i][0]
end

return frequent_elements
end


Expand Down
2 changes: 1 addition & 1 deletion test/exercises_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
end
end

xdescribe "top_k_frequent_elements" do
describe "top_k_frequent_elements" do
it "works with example 1" do
# Arrange
list = [1,1,1,2,2,3]
Expand Down