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 an Array INPUT n = 5 start = 0 Formula: nums[i] = start + 2*i Generated Array: 0 i=0 2 i=1 4 i=2 6 i=3 8 i=4 Binary Values: 0 = 0000 2 = 0010 4 = 0100 6 = 0110 8 = 1000 ALGORITHM STEPS 1 Initialize Result result = 0 2 Loop i: 0 to n-1 for i in range(5) 3 Compute Element num = start + 2*i 4 XOR with Result result ^= num XOR Computation: 0000 XOR 0000 = 0000 (0) 0000 XOR 0010 = 0010 (2) 0010 XOR 0100 = 0110 (6) 0110 XOR 0110 = 0000 (0) 0000 XOR 1000 = 1000 (8) Final: 8 FINAL RESULT XOR of all elements: 8 Binary: 1000 XOR Chain: 0 ^ 2 ^ 4 ^ 6 ^ 8 = 8 OK - Output: 8 Key Insight: Direct XOR without creating an array saves O(n) space. We compute each element on-the-fly using the formula nums[i] = start + 2*i and XOR it directly with the result. Time: O(n), Space: O(1). TutorialsPoint - XOR Operation in an Array | Direct XOR without Array Approach
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