Sobes.tech
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){ int result = 0; for(int num : arr){ result ^= num; } return result; }

sobes.tech AI

Answer from AI

The provided code uses the XOR (exclusive OR) operation to find the number that appears only once in the array, while all other numbers appear in pairs.

The idea is that XOR of two identical numbers gives 0, and XOR of a number with 0 gives the number itself. Therefore, by iterating through the entire array and applying XOR to all elements, only the number without a pair remains.

Example in Java:

int find(int[] arr) {
    int result = 0;
    for (int num : arr) {
        result ^= num; // XOR with the current number
    }
    return result;
}

// Usage:
// int[] arr = {1, 0, 3, -2, 9, 9, 1, -2, 0};
// System.out.println(find(arr)); // Will output 3

This method is efficient in terms of time (O(n)) and does not require additional memory.

// Given an array of numbers where all numbers except… - sobes.tech