Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Charlotte - Space #29

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 3 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
57 changes: 50 additions & 7 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,63 @@

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

Choose a reason for hiding this comment

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

This is most of the solution, the only weakness is that the sort_by you're doing doesn't preserve the order the elements were encountered in. You also have the time complexity wrong because you have a loop through all the elements and you're sorting them.

raise NotImplementedError, "Method hasn't been implemented yet!"
end
return [] if list.empty?

hash1 = {}

# create hash from list where same elements(key) are tallied(value)
list.each do |num|
if hash1[num]
hash1[num] += 1
else
hash1[num] = 1
end

end
# sort hash by value - descending
sorted = hash1.sort_by { |key, value| value }.reverse
answer = []
k.times do |index|
answer << sorted[index].first
end

return answer

end # closing end for top_k_frequent_elements method


# This method will return the true if the table is still
Expand Down