In this HackerRank Sparse Arrays problem, we need to develop a program in which for each gives string we need to determine how many times the query present in the string, and then we need to return an array as a result.
Example
There are instances of ‘, of ‘‘ and of ‘‘. For each query, add an element to the return array, .
Function Description
Complete the function matchingStrings in the editor below. The function must return an array of integers representing the frequency of occurrence of each query string in strings.
matchingStrings has the following parameters:
- string strings[n] – an array of strings to search
- string queries[q] – an array of query strings
Returns
- int[q]: an array of results for each query
Input Format
The first line contains and integer , the size of .
Each of the next lines contains a string .
The next line contains , the size of .
Each of the next lines contains a string .
Sparse Arrays Hacker Rank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
let lookUp = {};
for (let i = 0; i < strings.length; i++) {
if (lookUp.hasOwnProperty(strings[i])) {
lookUp[strings[i]] += 1;
} else {
lookUp[strings[i]] = 1;
}
}
let answer = [];
for (let i = 0; i < queries.length; i++) {
let frequency = lookUp[queries[i]];
if (frequency > 0) {
answer[i] = frequency;
} else {
answer[i] = 0;
}
}
return answer;
Problem Solution in Python
def matchingStrings(strings, queries):
result = []
for query in queries:
count = strings.count(query)
result.append(count)
return result
Leave a Reply