XOR Operation in an Array - Problem

You are given an integer n and an integer start.

Define an array nums where nums[i] = start + 2 * i (0-indexed) and n == nums.length.

Return the bitwise XOR of all elements of nums.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, start = 0
Output: 8
💡 Note: Array is [0,2,4,6,8]. XOR: 0⊕2⊕4⊕6⊕8 = 8
Example 2 — Different Start
$ Input: n = 4, start = 3
Output: 8
💡 Note: Array is [3,5,7,9]. XOR: 3⊕5⊕7⊕9 = 8
Example 3 — Single Element
$ Input: n = 1, start = 7
Output: 7
💡 Note: Array is [7]. XOR of single element is itself: 7

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ start ≤ 1000

Visualization

Tap to expand
XOR Operation in Array: Complete ProcessInputn = 5start = 0Generate024680+2*00+2*10+2*20+2*30+2*4XOR0 ⊕ 2 ⊕ 4 ⊕ 6 ⊕ 8= 8Output: 8XOR Properties: a ⊕ a = 0, a ⊕ 0 = a, XOR is commutativeBinary: 0000⊕0010⊕0100⊕0110⊕1000 = 1000 (8 in decimal)
Understanding the Visualization
1
Input
n=5, start=0 - generate 5 elements starting from 0
2
Generate Sequence
Create [0,2,4,6,8] using formula start + 2*i
3
XOR All
0⊕2⊕4⊕6⊕8 = 8
Key Takeaway
🎯 Key Insight: Generate arithmetic sequence with formula start + 2*i, then XOR all elements efficiently
Asked in
Amazon 15 Microsoft 12 Apple 8
23.5K Views
Medium Frequency
~10 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