Leetcode 1486. XOR Operation in an Array
The problem “1486. XOR Operation in an Array” is described as follows:
Given an integer n
and an integer start
. You need to construct an array nums
where nums[i] = start + 2 * i
(0-indexed) and n
is the size of the array. Return the bitwise XOR of all elements of the array.
n
and start
guaranteed to be non-negative integers?nums
using the formula nums[i] = start + 2 * i
.xor_result
to 0, and then iterate through the nums
array to continually XOR each element with xor_result
.#include <iostream>
class Solution {
public:
int xorOperation(int n, int start) {
int xor_result = 0;
for(int i = 0; i < n; ++i) {
xor_result ^= (start + 2 * i);
}
return xor_result;
}
};
int main() {
Solution solution;
std::cout << solution.xorOperation(5, 0) << std::endl; // Output: 8
std::cout << solution.xorOperation(4, 3) << std::endl; // Output: 8
std::cout << solution.xorOperation(1, 7) << std::endl; // Output: 7
std::cout << solution.xorOperation(10, 5) << std::endl; // Output: 2
return 0;
}
The time complexity of this solution is O(n), where n
is the size of the array. This is because we iterate through the array once to compute the XOR of all elements.
The space complexity is O(1) as we are not using any extra space that scales with input size, other than a few integer variables.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?