Koding Books

Professional, free coding tutorials

[ C++ ] Challenge | Variable Sized Arrays

Table of Contents

I had a few spare moments during my lunch hour; I didn’t feel particularly hungry, so let’s do a hacker rank challenge, I thought.

Problem

https://www.hackerrank.com/challenges/variable-sized-arrays

Half the challenge lies in decyphering the mathematical nonsense these types of challenges are wrapped in.

Algorithm

  1. Read the number of variable-length arrays n and the number of queries q from std::cin.
  2. Create a std::vector<std::vector<int>> data structure to store the variable-length arrays.
  3. For each variable-length array: a. Read the size of the array k from std::cin. b. Resize the vector to have a size of k. c. Read each array element from std::cin and store it in the vector.
  4. For each query: a. Read the indices x and y from std::cin. b. Print the element of the variable-length array at index y of the array at index x.

This algorithm reads the input, stores the variable-length arrays in a std::vector<std::vector<int>> data structure, and then processes each query by accessing the appropriate element of the appropriate array.

Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n, q;
    cin >> n >> q;

    vector<vector<int>> numbers(n);
    for (int i = 0; i < n; i++) {
        int k;
        std::cin >> k;
        numbers[i].resize(k);
        for (int j = 0; j < k; j++) {
            std::cin >> numbers[i][j];
        }
    }

    for (int i = 0; i < q; i++) {
        int x, y;
        cin >> x >> y;
        cout << numbers[x][y] << endl;
    }

    return 0;
}

All the tests should now pass, indicating that the challenge has been completed successfully.

Ali Kayani

https://www.linkedin.com/in/ali-kayani-silvercoder007/

Post navigation

Leave a Comment

Leave a Reply

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

Rust in Action

Digging into General Relativity with C++

Accumulation/Distribution Line indicator

C++ Pointers