Hackerrank - Sparse Arrays Solution
1 min read

Hackerrank - Sparse Arrays Solution

Hackerrank - Sparse Arrays Solution

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings.

For example, given input  and , we find  instances of ',  of '' and  of ''. For each query, we add an element to our 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:

  • strings - an array of strings to search
  • queries - an array of query strings

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 .

Constraints



.

Output Format

Return an integer array of the results of all queries in order.

Sample Input 1

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output 1

210

Explanation 1

Here, "aba" occurs twice, in the first and third string. The string "xzxb" occurs once in the fourth string, and "ab" does not occur at all.

Sample Input 2

3
def
de
fgh
3
de
lmn
fgh

Sample Output 2

101

Sample Input 3

13
abcde
sdaklfj
asdjf
na
basdn
sdaklfj
asdjf
na
asdjf
na
basdn
sdaklfj
asdjf
5
abcde
sdaklfj
asdjf
na
basdn

Sample Output 3

13432

Solution in python

from collections import Counter

def matchingStrings(strings, queries):
    c = Counter(strings)
    return (c[i] for i in queries)

n = int(input())
strings = [input() for _ in range(n)]
q = int(input())
queries = [input() for _ in range(q)]
print(*matchingStrings(strings, queries),sep="\n")

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×