Intuition¶
The solution leverages patterns in the XOR operation of specific sequences within an array. By recognizing these patterns, we can simplify the XOR computation, reducing the problem size and allowing for an efficient calculation.
Approach¶
Explanation:¶
- Pattern Analysis:
- Certain patterns in XOR operations simplify the problem. For instance, the XOR of numbers of the form
4xand4x + 2always results in2, while the XOR of numbers4x,4x + 2,4x + 4, and4x + 6results in0. -
Similarly, the XOR of
4x + 1and4x + 3is2, and extending this to4x + 1,4x + 3,4x + 5, and4x + 7yields0. -
Base Case Handling:
-
If
n == 1, the result is just thestartsince there's only one element. -
Initial Setup:
resis initialized to 0 and will store the XOR of selected elements.-
endis computed as the last element in thenumsarray (start + 2 * (n - 1)). -
Initial Check and Adjustments:
- If
start % 4 > 1, meaningstartis in the form of4x + 2or4x + 3, the XOR operation includesstartitself, andnis reduced by 1. -
Similarly, if
end % 4 <= 1, indicatingendis in the form of4xor4x + 1, the XOR operation includesend, andnis reduced by 1. -
Final XOR Computation:
- After the adjustments in the previous step,
nwill always be even, and according to the observed patterns, the XOR of the remaining elements will always result in either0or2. - The final XOR result is then computed by XOR-ing
reswithn % 4, following the pattern.
Complexity¶
- Time complexity: $O(1)$, since the computation involves a fixed number of steps.
- Space complexity: $O(1)$, as only a few variables are used.
Code¶
```cpp [] class Solution { public: int xorOperation(int n, int start) { if (n == 1) return start;
int res = 0;
int end = start + 2 * (n - 1);
if (start % 4 > 1) {
res ^= start;
--n;
}
if (end % 4 <= 1) {
res ^= end;
--n;
}
res ^= n % 4;
return res;
}
}; ```