XOR Operation in an Array

In this problem, we are given an integer n and an integer start. We need to define an array nums where each element is given by the formula nums[i] = start + 2 * i and return the bitwise XOR of all elements of nums.

Approach

  1. Initialize a variable result to hold the XOR result.
  2. Iterate over i from 0 to n-1, calculating each value start + 2 * i, and performing the bitwise XOR with result.
  3. Return the final result.

Here’s the code:

1
2
3
4
5
6
7
8
class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        result = 0

        for i in range(n):
            result ^= start + 2 * i

        return result

Example

For n = 5, start = 0, the array nums is [0, 2, 4, 6, 8], so the result is 0 ^ 2 ^ 4 ^ 6 ^ 8 = 8.

Complexity

This solution has a time complexity of O(N) and a space complexity of O(1), where N is the given integer n.