Single Number III

MediumBit Manipulation · XOR🧩 Bit ManipulationLeetCode #260 ↗Updated

Problem

You get an integer array nums in which exactly two values occur once and every other value occurs exactly twice. Return the two lonely values (in any order). Aim for linear time and constant extra space.
Input[1,2,1,3,2,5]Output[3,5]
Input[-1,0]Output[-1,0]
Input[0,1]Output[1,0]

2 ≤ n ≤ 3·104  ·  -231 ≤ nums[i] ≤ 231-1  ·  Follow-up: O(n) time, O(1) space.

Try it yourself

Java
class Solution {
    public int[] singleNumber(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
XOR of everything leaves a ^ b (pairs cancel). Any set bit of a ^ b is a bit where a and b differ — split the array on that bit and each half becomes the classic “one single number” problem.
PatternBit Manipulation

Instinct Pairs that cancel, counting 1s, powers of two, subsets as numbers, or 'no + or - allowed' - drop to binary and use XOR, AND, OR and shifts.

Memory hack XOR is a forgetful twin detector - see something twice and it vanishes; n & (n-1) snips off the last lit bulb.

Open the Bit Manipulation guide →

Approaches

Brute ForceCount Each Element by Rescanning

Time O(n2)Space O(1)

For every element, scan the whole array and count how many times it appears. The elements whose count is exactly 1 are the answer; stop once two are found.

Java
public int[] singleNumber(int[] nums) {
    int[] res = new int[2];
    int found = 0;
    for (int i = 0; i < nums.length && found < 2; i++) {
        int count = 0;
        for (int x : nums) {
            if (x == nums[i]) count++;
        }
        if (count == 1) res[found++] = nums[i];
    }
    return res;
}

Constant space and obviously correct, but quadratic time.

At a glance

LevelApproachTimeSpace
Brute ForceCount Each Element by RescanningO(n2)O(1)
BetterHash Map Frequency CountO(n)O(n)
OptimalXOR + Partition by Lowest Set BitO(n)O(1)
Common pitfalls
  • Writing num & diff == 1 — the masked value is diff, not 1; compare with 0.
  • Operator precedence: == binds tighter than &, so parenthesise (num & diff).
  • Comparing results order-sensitively — the two numbers may be returned in any order.
Interview tips
  • Recall Single Number I (XOR all) first, then ask: how do I separate two survivors?
  • Explain why duplicates never split: equal numbers share every bit, including diff.
  • Mention Integer.lowestOneBit(xor) as the readable equivalent of xor & -xor.
Pattern
XOR cancellation + bit partitioning → find unpaired elements among pairs in O(1) space.
My notes saved in this browser