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


Different Approaches:

Approach 1: Brute Force using Nested Loops

Check each element against all others and count occurrences manually.

class Solution { public int singleNumber(int[] nums) { for (int i = 0; i < nums.length; i++) { int count = 0; for (int j = 0; j < nums.length; j++) { if (nums[i] == nums[j]) count++; } if (count == 1) return nums[i]; } return -1; } }

Approach 2: Using a HashMap or HashSet

Store the count of each element in a map, then return the one that appears once.

class Solution { public int singleNumber(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) { map.put(num, map.getOrDefault(num, 0) + 1); } for (int key : map.keySet()) { if (map.get(key) == 1) return key; } return -1; } }

Approach 3: Using XOR (Optimal Solution)

Since duplicates cancel each other out with XOR, just XOR all elements — the result is the single number.

class Solution { public int singleNumber(int[] nums) { int result = 0; for (int num : nums) { result ^= num; } return result; } }

Approach 4: Math Trick (Set Sum - Array Sum)

Use the formula:
2 * (sum of unique elements) - (sum of all elements) = single number

class Solution { public int singleNumber(int[] nums) { Set<Integer> set = new HashSet<>(); int sumOfSet = 0, sumOfArray = 0; for (int num : nums) { if (!set.contains(num)) { set.add(num); sumOfSet += num; } sumOfArray += num; } return 2 * sumOfSet - sumOfArray; } }

⚠️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

ApproachTime 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

Popular posts from this blog

Trailing Zeros in Factorial – How Many and Why?

Divisible Drama — Who’s In, Who’s Out?

Zero Array After Queries