I've attempted to solve this HackerRank Sparse Arrays problem with Ruby.
I wanted to use #tally on the string_list array in order to create a hash of keys and their occurrence count. I have checked this works and prints to my console correctly:
string_list = ['ab', 'ab', 'abc']
string_count = string_list.tally
p string_count: {"ab"=>2, "abc"=>1}
My code is giving me the expected result of an array of integers locally, but when I submit my code to HackerRank it seems to throw a NoMethodError at the use of #tally.
Here is the error below:
Solution.rb:16:in `matchingStrings': undefined method `tally' for ["aba", "baba", "aba", "xzxb"]:Array (NoMethodError)
from Solution.rb:45:in `<main>'
Could anyone shed some light on why this is throwing an error?
Here is my full code solution, and the terminal output.
def matching_strings(string_list, queries)
string_count = string_list.tally
queries.map do |query|
string_count[query].nil? ? string_count[query] = 0 : string_count[query]
end
end
string_list = ['ab', 'ab', 'abc']
queries = ['ab', 'abc', 'bc']
p matching_strings(string_list, queries) : [2, 1, 0]
Thanks!