1. Bitwise XOR Reduction (Brute Force)
Intuition
By identity: x ^ x = 0 and x ^ 0 = x. Taking the XOR accumulator of the entire array cancels out every duplicate pair, leaving the single isolated element in O(n) time and O(1) space.
When to apply: Use to understand the parity cancellation property before exploiting sorted order.
Linear Frequency Counting (O(N) Time, O(N) Space)
2 of 2 questions left todayElements with frequency 2 are normal pairs
Elements with frequency 2 are normal pairs.
public class Main { public static class Solution { public int singleNonDuplicate(int[] nums) { int xor = 0; for (int x : nums) xor ^= x; return xor; } } public static void main(String[] args) { Solution sol = new Solution(); int[] nums = {1, 1, 2, 3, 3, 4, 4, 8, 8}; System.out.println("Single Element: " + sol.singleNonDuplicate(nums)); }}Time & Space Complexity
- Time complexity:
O(n)— A single linear pass XORing all n numbers. - Space complexity:
O(1)— O(1) memory for the XOR accumulator.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.