Sparse Array: Hackerrank(Solution)

Sparse Array: Hackerrank(Solution)

Sparse Array is problem-solving and data structure challenge of hackerank website. check out link To understand the solution checkout what is

Searches the container for elements with a value of k and returns the number of elements found. Because unordered_set containers do not allow for duplicate values, this means that the function actually returns 1 if an element with that value exists in the container, and zero otherwise.

Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.

Now,

This problem can be solved using two methods let’s see

1. using unordered_set STL

#include <iostream>
#include <iterator>
#include <unordered_set>
using namespace std;

int main() {
    // n - size of input string
    // q - size of queries string
    // i - iterator 
    int n, q, i;
    string strings;

    // defining unordered multiset container
    unordered_multiset<string> queries;
    cin >> n;
    for (i = 0; i < n; ++i) {
        cin >> strings;
        queries.insert(strings);
    }
   
    // asking the size of queries
    cin >> q;
    for (i = 0; i < q; ++i) {
        cin >> strings;
        // retrieval of same type of string count
        cout << queries.count(strings) << '\n';
    }
}

2. using map STL

#include <string>
#include <iostream>
#include <map>
using namespace std;

int main() {
    map<string,int> m;
    int n,q;
    string s;
    cin>>n;
    
    for(int i=0; i<n; i++){
        cin>>s;
        m[s]++;
    }
    
    cin>>q;
    for(int i=0;i<q;i++){
        cin>>s;
        cout<<m[s]<<endl;
    } 
    return 0;
}

2 Replies to “Sparse Array: Hackerrank(Solution)”

Leave a Reply

Your email address will not be published. Required fields are marked *