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
30 changes: 27 additions & 3 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,35 @@

# 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 words in strings, for the each loop
# I'm not sure what the time complexity is for string.chars.sort.join, but I would guess
# O(m), where m is the number of letters in strings

Choose a reason for hiding this comment

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

Not quite, remember the best sorts are O(m log m). You can make the argument that if the words are small, then the time complexity is O(n) where n is the number of words.

If the words are potentially long, then it could be O(n * m log m) where n is the number of words and m is the length of each word.

# if I am correct, that would be O(m*n) total
# If the words are as short as they are in the tests, we can assume that m is minimal enough
# for it to be nearly constant, resulting in a O(n) total.

# Space Complexity: O(n), where n is the number of words in strings

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

result = []
hash = {}
count = 0

strings.each do |string|
sorted_string = string.chars.sort.join

if hash[sorted_string]
result[hash[sorted_string]].push(string)
else
hash[sorted_string] = count
result.push([string])
count += 1
end
end

return result
end

# This method will return the k most common elements
Expand Down