Single Number in O(n) Time
Single Number — Find the Unique Element Using Bit Magic
Problem Statement
You're given a non-empty array of integers nums
.
Every element appears twice except for one.
Your task is to find the element that appears only once.
Best Technique – Bit Manipulation with XOR
Forget HashMaps, Sets, or sorting — the cleanest and most optimal way to solve this problem is using bitwise XOR (^
).
XOR Properties:
-
a ^ a = 0
→ a number XORed with itself cancels out -
a ^ 0 = a
→ a number XORed with 0 remains unchanged -
XOR is commutative and associative, so the order of operations doesn't matter
Approach 1: Brute Force using Nested Loops
Check each element against all others and count occurrences manually.
Approach 2: Using a HashMap or HashSet
Store the count of each element in a map, then return the one that appears once.
Approach 3: Using XOR (Optimal Solution)
Since duplicates cancel each other out with XOR, just XOR all elements — the result is the single number.
Approach 4: Math Trick (Set Sum - Array Sum)
Use the formula:
2 * (sum of unique elements) - (sum of all elements) = single number
⚠️Common Pitfalls
-
Using extra space (like HashMaps or Sets) breaks the constant space constraint.
-
Sorting the array is O(n log n), which doesn’t meet the linear time requirement.
-
Misunderstanding XOR behavior can lead to confusion. Know the properties well.
📊Time and Space Complexity
Approach | Time Complexity | Space Complexity | ||
---|---|---|---|---|
Brute Force | O(n²) | O(1) | ||
HashMap/HashSet | O(n) | O(n) | ||
XOR (Bit Manipulation) | O(n) | O(1) | ||
Math Trick (Set + Sum) | O(n) | O(n) |
🌍Real-World Applications
-
Error Detection: XOR is used in checksums, parity bits, and RAID systems
-
Low-level Programming: Bit manipulation is essential in embedded systems and OS internals
-
Technical Interviews: A favorite question that tests understanding of low-level operations and optimization
I hope you found this article insightful! Keep exploring, keep learning, and don’t forget to check back daily for more exciting problem breakdowns. If you know someone who would benefit from this, share it with them and help them grow too! That’s it for today—see you in the next post!
Signing off!!
Master DSA One Problem at a Time :)
Comments
Post a Comment