CMD Guide
HomeDSABit Manipulation

easy Single Number

Single Number

You are handed an array of integers in which every value appears exactly twice, except one value that appears once. Return that lone value. Example: [4, 1, 2, 1, 2]4. The interviewer will usually add the real constraint out loud: do it in linear time and constant extra space. That last clause is the whole game — it quietly rules out the obvious answers and points at exactly one tool: XOR.

The naive baselines (and why they cost)

Both work. Neither hits O(n) time and O(1) space. To get both, we stop tracking which numbers we've seen and instead accumulate a single running value that has the duplicates cancel themselves out. That accumulator is XOR.

The insight — why XOR isolates the loner (the proof)

XOR (^) has three algebraic properties, and together they are the entire solution:

Now XOR the entire array into one accumulator. Because we can reorder freely, mentally pull each duplicated pair next to itself. Every pair v ^ v collapses to 0 by self-inverse. What remains is 0 ^ 0 ^ … ^ loner, which by identity is just the loner. The duplicates annihilate themselves; the odd-one-out is the only thing that survives. No bookkeeping, one register, one pass.

Traced worked example — [4, 1, 2, 1, 2]

Keep a running accumulator acc, start at 0, XOR each element in array order. Watching the bits change is the point — notice the duplicates walking the accumulator right back to where it was:

stepelementelement (bin)acc beforeacc ^ element (bin)acc after (dec)
00000
14100000000 ^ 100 = 1004
21001100100 ^ 001 = 1015
32010101101 ^ 010 = 1117
41001111111 ^ 001 = 1106
52010110110 ^ 010 = 1004

Final acc = 100₂ = 4. Notice steps 2&4 (the two 1s) and steps 3&5 (the two 2s) each toggled a bit on then back off — net zero. Only the bit set by 4, which was never toggled a second time, remained. That is the cancellation proof made concrete.

Java: XOR fold

class Solution {
    public int singleNumber(int[] nums) {
        int acc = 0;
        for (int x : nums) {
            acc ^= x;          // duplicates cancel to 0; the loner survives
        }
        return acc;
    }
}

Go: XOR fold

package main

import "fmt"

func singleNumber(nums []int) int {
    acc := 0
    for _, x := range nums {
        acc ^= x // duplicates cancel to 0; the loner survives
    }
    return acc
}

func main() {
    fmt.Println(singleNumber([]int{4, 1, 2, 1, 2})) // 4
}

Complexity — derived from the code

One for loop over n elements; the body is a single XOR and assignment, each a one-cycle CPU instruction — O(1) per iteration. Total time = O(n). We keep exactly one int accumulator regardless of input size, so space = O(1). That is strictly better on memory than the hash-set baseline (O(n) space) and strictly better on time than the sort baseline (O(n log n)), and it needs only a single pass.

Judgment layer — when to reach for XOR, and when the hash set wins

Edge cases & traps

Takeaways


Authored from first principles on the XOR self-inverse/identity/associativity laws; both samples compiled and hand-traced on [4,1,2,1,2] → 4.

🧩 Pattern · Bit Manipulation

Recognize it: Presence / pairing / parity with XOR and masks → think in bits.

→ more Bit Manipulation problems, grouped
🤖 Don't fully get this? Learn it with Claude

Stuck on Single Number? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Single Number** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Single Number** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Single Number**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Single Number**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes