Variable Sized Arrays – HackerRank Solution

Variable Sized Arrays – HackerRank Solution

Problem :

Consider an n-element array, a, where each index i in the array contains a reference to an array of ki integers (where the value of ki varies from array to array). See the Explanation section below for a diagram.

Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array a and i denotes an index in the array located at a[i]. For each query, find and print the value of element j in the array at location a[i] on a new line.

Click here to know more about how to create variable sized arrays in C++.

Sample Input :

2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3

Sample Output :

5
9

Solution :

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int n; int q;
    cin >> n >> q;
    vector<int> a[n];
    int c; int b;
    for(int i = 0; i < n; i++) {
        cin >> b;
        for (int j = 0; j < b; j++) {
            cin >> c;
            a[i].push_back(c);
        }
    }
    int d; int e;
    for(int i = 0; i < q; i++) {
        cin >> d >> e;
        cout << a[d][e] << endl;
    }
    
    return 0;
}

 62 total views,  1 views today

Post Disclaimer

the above hole problem statement is given by hackerrank.com but the solution is generated by the SLTECHACADEMY authority if any of the query regarding this post or website fill the following contact form thank you.

Leave a Reply

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