Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example:
Input: nums = [2,2,1]
Output: 1
Input: nums = [4,1,2,1,2]
Output: 4
Input: nums = [1]
Output: 1
To solve this problem efficiently (O(n) time complexity and O(1) extra space), we can take advantage of the properties of the XOR bitwise operation:
a ^ a = 0
).a ^ 0 = a
).Thus, if we XOR all the numbers in the array, the numbers that appear twice will cancel out each other, leaving the single number as the result.
Here’s the implementation in C++:
#include <vector>
#include <iostream>
class Solution {
public:
int singleNumber(std::vector<int>& nums) {
int single = 0;
for (int num : nums) {
single ^= num; // XOR all elements
}
return single;
}
};
int main() {
Solution solution;
std::vector<int> test1 = {2, 2, 1};
std::cout << "Test 1: " << solution.singleNumber(test1) << std::endl; // Output: 1
std::vector<int> test2 = {4, 1, 2, 1, 2};
std::cout << "Test 2: " << solution.singleNumber(test2) << std::endl; // Output: 4
std::vector<int> test3 = {1};
std::cout << "Test 3: " << solution.singleNumber(test3) << std::endl; // Output: 1
return 0;
}
n
is the number of elements in the array. We only traverse the array once.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?