Dynamic Array | HackerRank




  • Create a list,, of empty sequences, where each sequence is indexed from to. The elements within each of the sequences also use -indexing.
  • Create an integer, and initialize it to.
  • The  types of queries that can be performed on your list of sequences () are described below:
    1. Query: 1 x y
      1. Find the sequence, at index in.
      2. Append integer to sequence.
    2. Query: 2 x y
      1. Find the sequence,  at index in.
      2. Find the value of the element in  (where is the size of ) and assign it to.
      3. Print the new value of  on a new line
Task
Given, and queries, execute each query.
Note:  is the bitwise XOR operation, which corresponds to the  ^ operator in most languages. Learn more about it on Wikipedia.
Input Format
The first line contains two space-separated integers,  (the number of sequences) and  (the number of queries), respectively.
Each of the subsequent lines contains a query in the format defined above.

Output Format
For each type of query, print the updated value of on a new line.
Sample Input
2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
Sample Output
7
3
Explanation
Initial Values:


 = [ ]
 = [ ]
Query 0: Append to sequence.

 = [5]
 = [ ]
Query 1: Append to sequence.
 = [5]
 = [7]
Query 2: Append to sequence.

 = [5, 3]
 = [7]
Query 3: Assign the value at the index of sequence to, print.

 = [5, 3]
 = [7]
7
Query 4: Assign the value at the index of sequence to, print.

 = [5, 3]
 = [7]
3

Solution (C++ 14)

#include <bits/stdc++.h>
using namespace std;
int main()
{
 int n,q;
 cin >> n >> q;

 vector <vector<int>>s(n,vector <int> ());
 int lastAnswer=0;
 for (int i=0;i<q;i++)
 {
    int t,x,y;
    cin >> t >> x >> y;

    if (t==1)
    {
        s[(x^lastAnswer)%n].push_back(y);
    }
    else
    {
        lastAnswer=s[(x^lastAnswer)%n][y%s[(x^lastAnswer)%n].size()];
        cout << lastAnswer << endl;
    }
  }
}

Comments

Popular posts from this blog

Boxes through a Tunnel | HackerRank

Array Manipulation | HackerRank

String Validators | HackerRank