We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Alright, here’s how I solved the Dynamic Array problem:
You start by creating n empty arrays and setting lastAnswer = 0. Then, you just go through each query one by one.
If the query type is 1, you find which array to use with this formula:
idx = (x ^ lastAnswer) % n
Then you just push y into that array.
If the query type is 2, you again use the same formula to find the array, but this time you read a value from it:
lastAnswer = arr[idx][y % arr[idx].size()]
and store or print that value.
Here’s what the code looks like (C++):
include
using namespace std;
int main() {
int n, q;
cin >> n >> q;
vector<vector<int>> arr(n);
int lastAnswer = 0;
while (q--) {
int type, x, y;
cin >> type >> x >> y;
int idx = (x ^ lastAnswer) % n;
if (type == 1) {
arr[idx].push_back(y);
} else {
lastAnswer = arr[idx][y % arr[idx].size()];
cout << lastAnswer << endl;
}
}
return 0;
}
That’s it. It’s basically about keeping track of the arrays using that XOR trick and knowing when to append or fetch values. Once you get that logic down, it’s pretty straightforward.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Dynamic Array
You are viewing a single comment's thread. Return to all comments →
Alright, here’s how I solved the Dynamic Array problem:
You start by creating n empty arrays and setting lastAnswer = 0. Then, you just go through each query one by one.
If the query type is 1, you find which array to use with this formula: idx = (x ^ lastAnswer) % n Then you just push y into that array.
If the query type is 2, you again use the same formula to find the array, but this time you read a value from it: lastAnswer = arr[idx][y % arr[idx].size()] and store or print that value.
Here’s what the code looks like (C++):
include
using namespace std;
int main() { int n, q; cin >> n >> q;
}
That’s it. It’s basically about keeping track of the arrays using that XOR trick and knowing when to append or fetch values. Once you get that logic down, it’s pretty straightforward.