Topic 13 of 14

Bit Manipulation Patterns

1 pattern and 5 practice problems, each with a recall tip, a diagram, the theory and a Python template.

01

Bit Manipulation - XOR Tricks

5 practice problems

Theory

  • a ^ a = 0, a ^ 0 = a. XOR of all elements cancels pairs — the unpaired element remains.
  • To find two unique numbers: XOR all, get a diff bit, partition into two groups by that bit.
  • XOR is its own inverse: if c = a ^ b, then a = c ^ b.
  • Useful for finding missing/duplicate numbers without extra space.

Code template

python
def single_number(nums):
    result = 0
    for num in nums:
        result ^= num
    return result

def missing_number(nums):
    n = len(nums)
    result = n
    for i in range(n):
        result ^= i ^ nums[i]
    return result

Practice problems · 5

Spotted a mistake on this page?

Wrong formula, broken animation or confusing wording. Tell us and we will fix it.