SPARSE ARRAY in C++

Updated: Nov 4

Sparse array in CPP | Array | Data Structure | C Plus Plus

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.


FOR EXAMPLE :

given input strings = [ab,ab,abc] and queries = [ab,abc,bc], we find 2 instances of ab,1 of abc and 0 of bc. For each query, we add an element to our return array, results = [2,1,0].


FUNCTION DISCRIPTION :

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 n, the size of strings.

Each of the next n lines contains a string string[i].

The next line contains q, the size of queries.

Each of the next q lines contains a string queries[i].


CONSTRAINT :

* 1<=n, q<=1000

* 1<=|string[i]|, queries[i]<=20.


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 : EXPLANATION

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



CODE SOLUTION :



#include<iostream>
using namespace std;
int main() {
    int n;
    
    cin >> n;
    string arr[n];
    for(int i=0; i<n; i++) {
        cin >> arr[i];
    }
    int q;
    cin >> q;
    string que[q];
    for(int i=0; i<q; i++) {
        cin >> que[i];
    }
    int freq[q] = {0};
    for(int i=0; i<q; i++) {
        for(int j=0; j<n; j++) {
            if(que[i]==arr[j]) {
                freq[i]+=1;
            } 
        }
        cout << freq[i] << endl;
    }
}


THERE YOU GO!!




25 views

Recent Posts

See All

"Believe you can and you're halfway there"