Algorithm Day97 - Single Number
🧩 Problem
LeetCode 136 - Single Number
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 linear runtime complexity and use only constant extra space.
Example:
1 | Input: nums = [4,1,2,1,2] |
💡 Idea
This problem can be elegantly solved using the XOR (^) operation.
Key properties of XOR:
a ^ a = 0a ^ 0 = a- XOR is commutative and associative
Thus, when we XOR all numbers together, pairs cancel out, leaving only the unique number.
Example
1 | nums = [4, 1, 2, 1, 2] |
💻 Java Code
1 | class Solution { |
🧠 Complexity
- Time: O(n) — iterate once through the array
- Space: O(1) — only one variable used
🏁 Summary
A perfect example of how bitwise operations simplify logic and improve efficiency.
The XOR trick is commonly used in array problems involving pairs and uniqueness detection.