Similar Problems

Similar Problems not available

Xor Operation In An Array - Leetcode Solution

Companies:

LeetCode:  Xor Operation In An Array Leetcode Solution

Difficulty: Easy

Topics: math bit-manipulation  

Problem Statement:

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.

Example: Input: n = 5, start = 0 Output: 8 Explanation: Array nums is equal to [0, 2, 4, 6, 8] where (0^2^4^6^8) = 8.

Solution:

To solve this problem, we just need to calculate the bitwise XOR of all elements in the array. We can calculate the array elements by adding (start + 2*i) to the array for each index i from 0 to n-1. At the same time, we can also keep calculating the XOR of the array elements using a variable called xorVal.

Here is the Python code to solve this problem:

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

Time Complexity:

The time complexity of this algorithm is O(n) as we need to iterate over all n elements of the array to calculate the XOR value.

Space Complexity:

The space complexity of this algorithm is O(1) as we are not using any additional space to store the array elements or XOR values.

Xor Operation In An Array Solution Code

1