#1486
XOR Operation in an Array
EasyMathBit ManipulationBit ManipulationArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of creating the entire array, we can directly compute the XOR using the properties of the XOR operation. This reduces both time and space complexity.
⚙️
Algorithm
2 steps- 1Step 1: Initialize a variable `result` to 0.
- 2Step 2: Iterate from 0 to n-1, calculating each element directly using the formula and updating `result` with the XOR of each element.
solution.py7 lines
1# Full working Python code
2
3def xorOperation(n, start):
4 result = 0
5 for i in range(n):
6 result ^= (start + 2 * i)
7 return resultℹ
Complexity note: The time complexity remains O(n) since we still iterate through `n` elements, but the space complexity is reduced to O(1) because we no longer need to store the entire array.
- 1Understanding the properties of XOR can simplify calculations.
- 2Direct computation can save time and space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.