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

Daniela - Leaves #36

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
40 changes: 37 additions & 3 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,45 @@

# 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: n^2 as for each word in the list I'm iterating over the letters.

# # Space Complexity: O(n) because if none of the words are anagrams,
# I will duplicate the array. Also, I will create a hash were each key is each word.


def grouped_anagrams(strings)

Choose a reason for hiding this comment

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

This is actually O(n * m) where m is the length of the strings. Or O(n) if the words are limited in size.

Good use of a hash as a key to another hash!

raise NotImplementedError, "Method hasn't been implemented yet!"
alphabet = {}
words_same_value = {}

index = 0
anagram_array = []
value = 0

strings.each do |word|
word_value = 0

word.each_char do |letter|
if alphabet[letter] == nil
alphabet[letter] = value + 1
value += 1
word_value += alphabet[letter]
else
word_value += alphabet[letter]
end
end

if words_same_value[word_value] == nil
words_same_value[word_value] = [word]
else
words_same_value[word_value] << word
end
end

words_same_value.keys do |sum|
anagram_array << sum
end

return anagram_array
end

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