Article start
DSA Course: Interview Patterns and Problem Solving
Module 14: Bit Manipulation

Single Number: XOR Cancellation Pattern

Find the one value that appears once when every other value appears twice.

May 29, 2026·25

Learning Outcome

After this lesson, you should be able to use XOR cancellation to remove duplicate pairs without extra memory.

Problem Statement

Given an integer array where every element appears twice except one, return the single element.

InputOutputWhy
nums = [4,1,2,1,2]41 cancels with 1, 2 cancels with 2, and 4 remains.

Brute Force Approach

Use a frequency map and return the value with count 1. This is clear but uses extra memory.

Optimized Approach

XOR every value. Because x xor x = 0 and x xor 0 = x, duplicate pairs cancel out and the unique value remains.

Exact Pseudocode

answer = 0
for x in nums:
  answer = answer xor x
return answer

Reference Code

class Solution:
    def singleNumber(self, nums):
        answer = 0
        for x in nums:
            answer ^= x
        return answer

Sample Dry Run

StepStateResult
Startanswer = 0No value processed
XOR 4,1,2answer changes with each valueTemporary result is not final yet
XOR second 1 and 2Duplicate pairs cancelOnly 4 remains
Returnanswer = 4single number found

Complexity

MeasureValueReason
TimeO(n)Each number is XORed once.
SpaceO(1)Only one answer variable is stored.

Edge Cases

  • The trick assumes every non-answer value appears exactly twice.
  • Negative numbers still work with XOR.
  • Do not use addition as a replacement for XOR cancellation.

Interview Checklist

  • Initialize answer to 0.
  • XOR every number exactly once.
  • State the XOR identities: x xor x = 0 and x xor 0 = x.

FAQs

Why does XOR remove duplicates?

Equal values XOR to zero, and XOR is associative and commutative, so pairs cancel regardless of order.

Why is space O(1)?

No map or set is needed; the running XOR holds the answer.

What is the core pattern?

XOR cancellation.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.

Lesson 1 of 5 in Module 14: Bit Manipulation