Sitemap
Arthi Murali

Arthi Murali

Data science enthusiast | Data engineering | Biomedical Science Graduate | Chemoinformatics

Hackerrank Data Structure - Sparse Arrays

2 min readApr 18, 2023

--

Finding the frequency of a string in an array

Problem

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. Return an array of the results.

Example:

strings=[‘ab’, ‘ab’, ‘abc’]
queries=[‘ab’, ‘abc’, ‘bc’]

There are instances of ‘ab’, 1 of ‘abc’ and 0 of ‘bc’. For each query, add an element to the return array, results=[2,1,0].

Input Format:

The first line contains and integer n, the size of strings[].
Each of the next n lines contains a string strings[i].
The next line contains q, the size of queries[].
Each of the next q lines contains a string queries[i].

Constraints

1<=n<=1000
1<=q<=1000
1<=strings[i],queries[i]<=20.

Get Arthi Murali’s stories in your inbox

Join Medium for free to get updates from this writer.

Sample Input

Press enter or click to view image in full size

Sample Output

2
1
0

Solution

n = int(input())
strings = []
for i in range(n):
strings.append(input())

q = int(input())
queries = []
for i in range(q):
queries.append(input())

counts = {}
for s in strings:
if s in counts:
counts[s] += 1
else:
counts[s] = 1

results = []
for q in queries:
if q in counts:
results.append(counts[q])
else:
results.append(0)
for i in results:
print(i)

Explanation

The input is taken as integer and assigned to n. An empty list is initialized to the variable strings. The loop runs n times and takes n number of string as input and appends to variable strings.

The input is taken as integer and assigned to q. An empty list is initialized to the variable queries. The loop runs q times and takes q number of string as input and appends to variable queries.

An empty dictionary is stored in the variable counts. A loop iterates through strings and checks if a string is in counts , if yes the value of the key of the string is incremented by +1. If, key not in counts, the value to the key is set as 1.

An empty list is stored in variable results. The loop iterates through queries. If query is in counts , the value count of the key is appended to results. Else, 0 is appended to results.

The loop iterates through results and prints the results in vertical order.

I hope this blog helps. Do let me know if there is any feedback or any other approach to this problem. Would love to learn :)

--

--

Arthi Murali
Arthi Murali

Written by Arthi Murali

Data science enthusiast | Data engineering | Biomedical Science Graduate | Chemoinformatics