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

Fire - Jing #13

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
29 changes: 25 additions & 4 deletions lib/exercises.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,40 @@

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

👍 Interesting use of a hash as a key for a hash.

raise NotImplementedError, "Method hasn't been implemented yet!"
words = Hash.new

strings.each do |string|
letter_count = Hash.new
string.each_char do |c|
letter_count[c] = letter_count[c] ? letter_count[c] + 1 : 1
end

if words[letter_count]
words[letter_count].push(string)
else
words[letter_count] = [string]
end
end

return words.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: ?
def top_k_frequent_elements(list, k)
Comment on lines 26 to 30

Choose a reason for hiding this comment

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

This mostly works, but it doesn't pass all the tests because it doesn't select the 1st element which appears the most times, in case of a tie.

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

list.each do |element|
element_count[element] = element_count[element] ? element_count[element] + 1 : 1
end

return element_count.max_by(k) {|a| a[1]}.map {|a| a[0]}
end


Expand Down