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

Space - Hala #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
52 changes: 46 additions & 6 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,59 @@

# 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(n2)
# Space Complexity: O(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.

👍 This works, but you can do better by sorting the words and using the sorted letters as keys for all the anagrams

raise NotImplementedError, "Method hasn't been implemented yet!"
hashOfArrays = {}
strings.each do |string|
key = string.split("")
unless hashOfArrays.keys.include?(key)
hashOfArrays.values do |array|
internalArr = array[0].split("")
count = 0
internalArr.each do |char|
if !string.include?(char)
count +=1
end
end
if count == internalArr.length
array<< string
end
end
end
end

return hashOfArrays.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(n2)
# Space Complexity: O(n)
def top_k_frequent_elements(list, k)
Comment on lines +32 to 34

Choose a reason for hiding this comment

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

Your solution has 3 loops which each run n times. It also sorts the array. So the method is O(n log n) in time complexity.

raise NotImplementedError, "Method hasn't been implemented yet!"
numHash = {}
returnList = []
list.each do |num|
if numHash.keys.include?(num)

Choose a reason for hiding this comment

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

Can be simplified

Suggested change
if numHash.keys.include?(num)
unless numHash[num].nil?

numHash[num]+=1
else
numHash[num]=1
end
end

numHash.sort.reverse

numHash.keys.each do |num|
if returnList.length < k
returnList<< num

Choose a reason for hiding this comment

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

Suggested change
returnList<< num
returnList<< num

else
return returnList
end
end

return returnList

end


Expand Down