Dynamic Array in C hackerrank solution

      

  #include <stdio.h>
  #include <stdlib.h>
  
  int main() {
      int n, q;
      scanf("%d %d", &n, &q);
  
      int **arr = (int **)malloc(n * sizeof(int *));
  
      for (int i = 0; i < n; i++) {
          int k;
          scanf("%d", &k);
  
          arr[i] = (int *)malloc(k * sizeof(int));
  
          for (int j = 0; j < k; j++) {
              scanf("%d", &arr[i][j]);
          }
      }
  
      for (int i = 0; i < q; i++) {
          int x, y;
          scanf("%d %d", &x, &y);
  
          printf("%d\n", arr[x][y]);
      }
  
      for (int i = 0; i < n; i++) {
          free(arr[i]);
      }
      free(arr);
  
      return 0;
  }
              
            

Let's go through the solution step by step:

We include the and header files to use the standard input/output functions and dynamic memory allocation functions.

In the main() function, we declare two integers n and q to store the number of sequences and number of queries, respectively.

We use the scanf() function to read the values of n and q from the user.

We dynamically allocate a 2D array arr using the malloc() function. The arr is an array of n integer pointers.

We use a for loop to iterate n times, where n represents the number of sequences. Inside the loop, we perform the following steps:

a. We declare an integer k to store the size of the current sequence.

b. We use the scanf() function to read the value of k from the user.

c. We dynamically allocate an array of size k for the current sequence using the malloc() function. The arr[i] represents the ith sequence.

d. We use another for loop to iterate k times, where k represents the size of the current sequence. Inside this loop, we use the scanf() function to read the values of each element of the sequence.

We use another for loop to iterate q times, where q represents the number of queries. Inside this loop, we perform the following steps:

a. We declare two integers x and y to store the query indices.

b. We use the scanf() function to read the values of x and y from the user.

c. We use the printf() function to print the value of arr[x][y], which corresponds to the element at index y of the xth sequence.

After executing all queries, we use a for loop to free the memory allocated for each sequence using the free() function. This ensures that we release the dynamically allocated memory to avoid memory leaks.

Finally, we use the free() function to free the memory allocated for the array of pointers.

By providing the expected input and executing the code, you should see the desired output according to the problem statement on HackerRank.