Senior
//Given an array of numbers where all numbers except one have a pair, //find the number that appears only once // // // <= [1, 0, 3, -2, 9, 9, 1, -2, 0] // // => 3 int find(int[] arr){ Map<Integer,
sobes.tech AI
Answer from AI
Task: find the single number in an array that does not have a pair (all others appear twice).
The optimal solution is to use the XOR operation (exclusive OR). Properties of XOR:
- a ^ a = 0
- a ^ 0 = a
- XOR is commutative and associative
Therefore, if you perform XOR on all elements of the array, pairs will cancel each other out, leaving only the number without a pair.
Example in Java:
int find(int[] arr) {
int result = 0;
for (int num : arr) {
result ^= num;
}
return result;
}
// Example usage: // int[] arr = {1, 0, 3, -2, 9, 9, 1, -2, 0}; // find(arr) will return 3
This solution works in O(n) time and O(1) space.