↓Skip to main content
  1. LeetCode/

LeetCode 1486: XOR Operation in an Array

·1 min· ·
LeetCode Easy Math Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-12-18

  • Submissions: Accepted (Python) → Accepted (C++) → Wrong Answer (C++) → Accepted (C++)

Approach
#

The i-th number is start + 2 * i, and n is at most 1000, so XOR them one by one.

My Attempts
#

Both Python and C++ passed first; rewriting the C++ later, I typed n * i instead of 2 * i. For n = 5, start = 0 the answer is 0 ^ 2 ^ 4 ^ 6 ^ 8 = 8; that version computed 0 ^ 5 ^ 10 ^ 15 ^ 20 = 20.

Solution
#

class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        res = 0
        for i in range(n):
            res ^= start + 2 * i
        return res

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • The step is a fixed 2, not n.

Interview Explanation
#

Generate each start + 2i by definition and accumulate the XOR in one variable. n is small so O(n) is enough; for O(1) there is the periodic formula for 1 ^ 2 ^ ... ^ k.

Related

LeetCode 342: Power of Four
·1 min
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 342 note: confirm a power of two, then that the single 1 sits at an even position: n & 0x55555555 != 0, or n % 3 == 1
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 231: Power of Two
·2 mins
LeetCode Easy Math Bit-Manipulation Recursion
LeetCode 231 note: a power of two has exactly one set bit, and n & (n - 1) clears the lowest one, so the result is 0 exactly then; n must be positive
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 1290: Convert Binary Number in a Linked List to Integer
·2 mins
LeetCode Easy Linked-List Bit-Manipulation Math
LeetCode 1290 note: walk head to tail, shifting the running value left by one and adding the new bit
LeetCode 762: Prime Number of Set Bits in Binary Representation
·1 min
LeetCode Easy Math Bit-Manipulation Primality-Test
LeetCode 762 note: numbers are below 10^6 < 2^20, so the set-bit count is at most 19; check it against a small set of primes