XOR Operation in an Array - Problem

You're tasked with performing a bitwise XOR operation on a specially constructed array. Given two integers n and start, you need to:

  1. Create an array nums of length n where each element follows the pattern: nums[i] = start + 2 * i
  2. Return the XOR of all elements in this array

Example: If n = 5 and start = 0, the array becomes [0, 2, 4, 6, 8], and the XOR result is 0 ⊕ 2 ⊕ 4 ⊕ 6 ⊕ 8 = 8.

This problem tests your understanding of bit manipulation and mathematical patterns in XOR operations. Can you find an efficient solution that goes beyond the obvious approach?

Input & Output

example_1.py — Basic Case
$ Input: n = 5, start = 0
Output: 8
💡 Note: Array becomes [0, 2, 4, 6, 8]. XOR: 0 ⊕ 2 ⊕ 4 ⊕ 6 ⊕ 8 = 8
example_2.py — Small Array
$ Input: n = 4, start = 3
Output: 8
💡 Note: Array becomes [3, 5, 7, 9]. XOR: 3 ⊕ 5 ⊕ 7 ⊕ 9 = 8
example_3.py — Single Element
$ Input: n = 1, start = 7
Output: 7
💡 Note: Array has only one element [7], so XOR result is 7

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ start ≤ 1000
  • nums[i] = start + 2 * i for all valid indices i

Visualization

Tap to expand
XOR Operation Factorystartstart+2start+4...XOR GATERESULTEach number flows through the XOR gate, accumulating the final result
Understanding the Visualization
1
Generate Sequence
Create arithmetic sequence: start, start+2, start+4, ...
2
XOR Accumulation
Pass each number through XOR gate with running result
3
Final Output
The last XOR result is our answer
Key Takeaway
🎯 Key Insight: XOR operations can be computed incrementally - we don't need to store the entire array, just accumulate the XOR result as we generate each element.
Asked in
Amazon 25 Microsoft 18 Apple 12 Google 8
28.5K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen