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.
To achieve a solution with linear runtime complexity ((O(n))) and constant extra space ((O(1))), you can use the XOR bitwise operation. XOR has a few useful properties:
With these properties, XORing all the elements in the array will cancel out all elements that appear twice, leaving the single number that appears only once.
public class SingleNumber {
public int singleNumber(int[] nums) {
int result = 0;
for (int num : nums) {
result ^= num;
}
return result;
}
// Example usage
public static void main(String[] args) {
SingleNumber solution = new SingleNumber();
int[] nums = {4, 1, 2, 1, 2};
System.out.println(solution.singleNumber(nums)); // Output will be 4
}
}
result
to 0.num
in nums
, XOR it with result
.result
will hold the number that appears only once.By using the XOR operation, we ensure that our solution is both time-efficient and space-efficient.
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?