</>

136. Single Number

Easy NeetCode 150
Bit Manipulation Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Bit Manipulation
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven an integer array where every element appears exactly twice except for one, find and return that lone element.

Approach
  • XOR every element together into a running accumulator.
  • Because x ^ x == 0 for any value and x ^ 0 == x, all paired duplicates cancel out, leaving only the unique element.
  • This works in a single pass with no extra memory, regardless of element order or value range.
#include <vector>
using namespace std;

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int result = 0;
        for (int n : nums) {
            result ^= n;   // paired values cancel (x ^ x == 0); lone value survives
        }
        return result;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        // A^A=0
        int ans=0;
        for(const int& n: nums){
            ans^=n;
        }
        return ans;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern