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.
- Prepare
- Data Structures
- Arrays
- Dynamic Array
- Discussions
Dynamic Array
Dynamic Array
Sort by
recency
|
2075 Discussions
|
Please Login in order to post a comment
The problem definition is incorrect.
The problem definition is incorrect.
It states that: idx = (x ⊕ lastAnswer)
But it should read: idx = (x ⊕ lastAnswer) % n
where n is one of the input variables.
If you're having trouble with this question it is not your fault. idx should be = (x ^ lastAnswer) % n not just (x ^ lastAnswer) as stated in the problem. So annoying.
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.
The problem is simple but the description is kinda confusing and it is not mentionned to do modulo n for the index unless u see it in the example got me stuck for a while since my idx got out of range :D