Leetcode 3158. Find the XOR of Numbers Which Appear Twice
You are given an array of integers nums
where every element appears exactly twice except for one element which appears once. Find the element that appears once.
nums
can go up to 10^6
.-10^6
to 10^6
.We can leverage the XOR bitwise operator to solve this problem efficiently:
XOR Property: a ^ a = 0
and a ^ 0 = a
. This means that if we XOR all the numbers together, the numbers that appear twice will cancel each other out, leaving us with the number that appears only once.
Time Complexity: Since we only need a single pass through the array to compute the XOR, the time complexity is O(n), where n is the number of elements in the array.
Space Complexity: We do not need any extra space other than a few variables for the XOR computation, so the space complexity is O(1).
Here is the C++ implementation of the solution:
#include <iostream>
#include <vector>
int findUniqueNumber(const std::vector<int>& nums) {
int uniqueNumber = 0;
for (int num : nums) {
uniqueNumber ^= num;
}
return uniqueNumber;
}
int main() {
std::vector<int> nums;
int n;
std::cout << "Enter the number of elements: ";
std::cin >> n;
std::cout << "Enter the elements: ";
for (int i = 0; i < n; ++i) {
int x;
std::cin >> x;
nums.push_back(x);
}
int result = findUniqueNumber(nums);
std::cout << "The element that appears once is: " << result << std::endl;
return 0;
}
n
and then populate the nums
array with n
integers.uniqueNumber
to 0 and iterate through all elements in nums
, applying the XOR operation to uniqueNumber
and each element. After the loop, uniqueNumber
will hold the element that appears only once.By following this approach, we can efficiently determine the unique element in the array using XOR properties.
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?