## Saturday, 6 February 2016

### Sparse Arrays Hacker Rank Problem Solution Using C++.

There are N strings. Each string's length is no more than 20 characters. There are also Qqueries. For each query, you are given a string, and you need to find out how many times this string occurred previously.
Input Format
The first line contains N, the number of strings.
The next N lines each contain a string.
The N+2nd line contains Q, the number of queries.
The following Q lines each contain a query string.
Constraints
1N1000
1Q1000
1 length of any string20
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.

Solution:

#include<bits/stdc++.h>
using namespace std;
/*
*
* Prosen Ghosh
* American International University - Bangladesh (AIUB)
*
*/
int main(){

map<string,int>m;
int n,q;
string str;

cin >> n;
for(int i = 0; i < n; i++){
cin >> str;
m[str]++;
}
cin >> q;
for(int i = 0; i < q; i++){
cin >> str;
cout << m[str] << endl;
}
return 0;
}

1. can you explain your code?
I am weak in stl..

2. can you explain your code?
I am weak in stl..

3. can you explain your code?
I am weak in stl..

4. map is a key:value pair container,In a map, the key values are generally used to uniquely identify the elements, while the mapped values store the content associated to this key.

Explanation Of my code:
when i am taking input in the 1st loop i increment the key value by 1. Example: m["aba"]++; it will increment the "aba" key value by 1.And in the 2nd loop i just print the key value.

1. Good one! Thanks

6. This comment has been removed by the author.

8. m["aba"]++; it will increment the "aba" key value by 1 => but in the declaration of map,key is string I think... Actually I'm unable to understand how m[str]++ increased the value of key??

9. another simple code using STL but without maps
int n,q,count=0;
cin>>n;
string words[n];
for(int i=0;i>words[i];
}
cin>>q;
string words1[q];
for(int j=0;j>words1[j];
for(int i=0;i<n;i++)
{
if(words1[j]==words[i])
count++;
}
cout<<count<<endl;
count=0;

10. Beautiful!