AlgoViz

Bitwise XOR

easy 14 min

XOR compares two numbers bit by bit and outputs 1 wherever they differ.

See it run

Fold [4, 1, 2, 1, 2] into one variable until only 4 is left, work out 5 XOR 3 one column at a time, swap two numbers with three XORs, and find the missing number in [3, 0, 1].

Operations

Find single number

Every value in [4, 1, 2, 1, 2] appears twice except one. XOR everything into one variable: pairs cancel because $a \oplus a = 0$, and the survivor is the answer. One pass, one variable.

Step 1 of 8

The problem: one value has no partner

  1. 40
  2. 11
  3. 22
  4. 13
  5. 24
result = 0 (000)

In [4, 1, 2, 1, 2] every number appears twice except one. We want it in O(n) time and O(1) extra space, so no hash set. Start with result = 0, because XOR with 0 leaves a number unchanged.

Step 1: The problem: one value has no partner

def single_number(nums):    result = 0    for num in nums:        result ^= num    return result
Time
O(n)
Space
O(1)
hash set
O(n) time, O(n) space
sort first
O(n log n) time

If a problem says "every element appears twice except one" and asks for O(1) space, the answer is a running XOR.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Using ^ as a power operator

    critical

    In Python, C, Java and JavaScript, ^ is bitwise XOR. 2 ^ 3 is 1, not 8. Powers are ** in Python and Math.pow or a loop elsewhere.

    Wrong
    area = side ^ 2      # XOR: 5 ^ 2 == 7
    Right
    area = side ** 2     # 25
  • XOR-swapping a slot with itself

    critical

    When i == j, arri ^= arrj computes x ^ x = 0 and the value is gone. Shuffles and partition code hit this whenever both indexes coincide.

    Wrong
    arr[i] ^= arr[j]arr[j] ^= arr[i]arr[i] ^= arr[j]     # arr[i] becomes 0 when i == j
    Right
    if i != j:    arr[i] ^= arr[j]    arr[j] ^= arr[i]    arr[i] ^= arr[j]# or simply: arr[i], arr[j] = arr[j], arr[i]
  • Using the pair trick when duplicates come in threes

    major

    XOR only cancels values that appear an even number of times. In [2, 2, 3, 2] the three 2s leave a 2 behind, so the fold gives 2 ^ 3 = 1. Triples need per-bit counting modulo 3.

    Wrong
    def single(nums):           # every other value appears 3 times    r = 0    for x in nums:        r ^= x    return r                  # single([2, 2, 3, 2]) == 1
    Right
    def single(nums):           # count each bit modulo 3    ans = 0    for k in range(32):        if sum((x >> k) & 1 for x in nums) % 3:            ans |= 1 << k    return ans if ans < 2**31 else ans - 2**32
  • Starting the accumulator at the wrong value

    major

    XOR's identity is 0, not 1. Starting at 1 flips bit 0 of the answer. In missing number, forgetting to seed with n leaves index n out of the cancellation.

    Wrong
    result = 1              # flips bit 0result = 0              # missing_number([0, 1]) returns 0, not 2
    Right
    result = 0              # single numberresult = len(nums)      # missing number: include index n
  • Forgetting operator precedence

    minor

    Arithmetic and shifts bind tighter than ^ in Python, so a ^ b + 1 means a ^ (b + 1). Parenthesise mixed expressions; in C and Java, == even binds tighter than ^.

    Wrong
    x = a ^ b + 1        # a ^ (b + 1)mask = 1 << k + 1     # 1 << (k + 1)
    Right
    x = (a ^ b) + 1mask = (1 << k) + 1
  • Clearing the lowest set bit when you meant to isolate it

    major

    x & (x - 1) removes the lowest 1 bit; x & -x keeps only that bit. Single Number III needs the isolated bit to split the array into two groups.

    Wrong
    diff = xor_all & (xor_all - 1)   # 6 -> 4, clears the bit
    Right
    diff = xor_all & -xor_all        # 6 -> 2, isolates it

Interview tips

  • Spot it fast

    • "Every element appears twice except one" with O(1) space.
    • "Numbers 0 to n, one is missing" or "one is duplicated".
    • Find where two numbers differ, or count differing bits (Hamming distance).
    • Toggle a flag or a bit: x ^= 1 << k.
  • Properties to know cold

    • Self-cancelling: a ⊕ a = 0. Identity: a ⊕ 0 = a.
    • Commutative and associative: order and grouping never matter.
    • Its own inverse: (a ⊕ b) ⊕ b = a.
    • No carries: every bit position is independent.
  • Say it in the interview

    • "Pairs cancel because a XOR a is 0, and order does not matter because XOR is commutative and associative."
    • Compare with the hash set: same O(n) time, but O(1) instead of O(n) space.
    • Mention the limits: only even repeats cancel, and the XOR swap fails on aliased memory.
  • Watch out

    • ^ is XOR, never a power, in Python, C, Java and JavaScript.
    • Parenthesise expressions that mix ^ with +, -, << or ==.
    • Python ints are unbounded, so masks like & 0xFFFFFFFF are needed to mimic 32-bit results.