We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

XOR Operation in an Array

Number: 1610

Difficulty: Easy

Paid? No

Companies: Walmart Labs


Problem Description

Given integers n and start, define an array nums where nums[i] = start + 2 * i (0-indexed) and n equals the length of nums. Return the bitwise XOR of all elements in the array.


Key Insights

  • XOR is commutative and associative, meaning the order of operations does not affect the result.
  • No need to actually build the array; each element can be computed on-the-fly.
  • Iteratively applying the XOR operation for each computed element gives a time-efficient solution.
  • The operation uses constant additional space.

Space and Time Complexity

Time Complexity: O(n) Space Complexity: O(1)


Solution

The approach is to initialize a variable result to 0 and iterate from 0 to n-1. In each iteration, calculate the current element using start + 2 * i and then XOR it with the result. Finally, return the result after processing all elements. This method leverages the properties of XOR and does not require extra memory for the array.


Code Solutions

def xorOperation(n: int, start: int) -> int:
    # Initialize result as 0.
    result = 0
    # Loop through each index to compute the XOR.
    for i in range(n):
        # Compute the current element of the array.
        current_num = start + 2 * i
        # XOR the current element with the cumulative result.
        result ^= current_num
    # Return the final XOR result.
    return result

# Example usage:
print(xorOperation(5, 0))  # Output: 8
← Back to All Questions