Skip to main content

Single Number

Problem Statement:​

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 a linear runtime complexity and use only constant extra space.

  • Example:

    Example 1:

    Input: nums = [2,2,1]

    Output: 1

    Example 2:

    Input: nums = [4,1,2,1,2]

    Output: 4

    Example 3:

    Input: nums = [1]

    Output: 1


✅ Solution: Bit Manipulation (Using XOR)​

class Solution {
public:
int singleNumber(vector<int>& nums) {
int xorResult = 0;

for (auto num : nums) {
xorResult ^= num; // XOR all numbers
}

return xorResult; // The unique number remains
}
};


📝 How It Works​

  • The XOR (^) operation has two key properties:
    • a ^ a = 0 (any number XOR with itself is 0)
    • a ^ 0 = a (any number XOR with 0 remains unchanged)
  • In this problem:
    • Every number appears twice except one.
    • XORing all numbers cancels out the duplicates and leaves only the single number.

🧩 Key Formula / Logic​

xorResult ^= nums[i]; // cancels out all duplicates

Result = element that appears once.


⏱️ Time & Space Complexity​

MetricComplexity
TimeO(N)
SpaceO(1)

Just one pass and constant memory.


⚠️ Edge Cases​

  • Array with only one element.
  • All pairs except one → the algorithm handles it naturally.

💡 Other Approaches​

ApproachTimeSpaceNotes
Hash Map FrequencyO(N)O(N)Easy to implement, slower
Sorting + ScanO(N log N)O(1)Extra time for sorting
XOR ✅O(N)O(1)Best and most elegant


🛠️ Real-world Analogy​

Imagine everyone in a room shakes hands twice with each other — except one person who only shakes hands once. XOR lets you magically detect who it is by pairing and canceling out all handshakes.

🚀 Level Up Your Engineering Mindset

Never Study in Isolation. Join Binary Dose.

Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.

Discord
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚡
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

💡Have handwritten notes, cheat-sheets, or want to publish a technical article?
Learn How to Contribute→