Sparse Arrays[HackerRank Solution]

1–2 minutes

read

Sparse Arrays[HackerRank Solution]

Problem:

There is a collection of N strings ( There can be multiple occurences of a particular string ). Each string’s length is no more than 20 characters. There are also Q queries. For each query, you are given a string, and you need to find out how many times this string occurs in the given collection of N strings.

Input Format

The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2 line contains Q, the number of queries.
The following Q lines each contain a query string.

 

Sample Input

4
aba
baba
aba
xzxb
3
aba
xzxb
ab

Sample Output

2
1
0

Explanation

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.

 

Code:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<bits/stdc++.h>
using namespace std;

int main() {
 // Enter your code here. Read input from STDIN. Print output to STDOUT 
 map<string,int> m;
 string s,p;
 int n;
 cin>>n;
 for(int i=0;i<n;i++)
 {
 cin>>s;
 m[s]++;
 }
 int q;
 cin>>q;
 for(int i=0;i<q;i++)
 {
 cin>>p;
 cout<<m[p]<<endl;
 }
 return 0;
}

Voila!

2 responses to “Sparse Arrays[HackerRank Solution]”

  1. I enjoy you because of all your valuable effort on this website. My mother takes pleasure in participating in internet research and it’s really simple to grasp why. We know all about the compelling manner you give functional secrets on the web blog and welcome response from people on this area plus our girl is actually learning a lot of things. Enjoy the remaining portion of the year. You’re the one doing a useful job.

    Like

  2. wohh just what I was looking for, regards for putting up.

    Like

Leave a comment