Skip to contentKEEP THE CRAFTTHE SANCTUARY

Bit Manipulation

Give each bit a precise meaning before using masks, shifts or XOR. Distinguish logical from bitwise operations, setting from toggling, fixed-width complements, and parity cancellation in an integer fold.

3 practice exercises5 interview problems

Recognize it when A compact state consists of independent yes/no flags.

Checking your account…

Bit Manipulation Code Labs

Treat Integers as Bit Sets

A bit position represents one Boolean flag inside an integer. Build masks with one shifted by the zero-based index and name which position each mask owns.

Test Set and Clear One Bit

Test with AND, set with OR, clear with AND against the inverted mask, and toggle with XOR. Parenthesize shifts and combinations so precedence is visible.

Trace Bit Operations

Reference
def bit_operations(value,index):
    mask=1<<index
    return [bool(value&mask),value|mask,value&~mask,value^mask]
Practice

Implement bit_operations(value,index). Return [tested,set_value,cleared_value,toggled_value] for the selected zero-based bit. The zero-based index must be a nonnegative integer.

Public tests

  • Apply one explicit mask

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Bit Operations

def bit_operations(value,index):
    mask=1<<index
    return [bool(value&mask),value|mask,value&~mask,value^mask]

Use XOR for Parity and Cancellation

XOR is associative, commutative, and self-canceling: x XOR x is zero. It can isolate one unpaired value when every other value appears exactly twice, but the frequency premise is essential.

Find the Unpaired Value

Reference
def single_unpaired(values):
    result=0
    for value in values:result^=value
    return result
Practice

Implement single_unpaired(values). Every integer appears twice except one; return the singleton using XOR.

Public tests

  • Cancel equal pairs with XOR

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find the Unpaired Value

def single_unpaired(values):
    result=0
    for value in values:result^=value
    return result

Watch Nonadjacent Pairs Cancel

Use the existing XOR Lab on [6, 3, 6, 5, 3]. Write the accumulator after each value before running it. Every other value occurs exactly twice, as required by this Lab. A second singleton call confirms that the initial zero does not erase a value.

Step Executed statement State Why
Identity result=0 result=0 Zero contributes no bits to XOR.
First two values result^=value after 6: 6; after 3: 5 The accumulator is the XOR of the processed prefix, not its sum.
Second 6 result^=value result=3 The two 6 values cancel even though another value separated them.
Consume 5 and 3 result^=value after 5: 6; after 3: 5 The pair of 3 values now cancels, leaving only 5.
Return return result 5 The parity premise makes this remaining XOR the requested unpaired value.
Print Output
print(single_unpaired([6, 3, 6, 5, 3])) 5
print(single_unpaired([9])) 9

Cancellation is a contract-dependent shortcut. If two different values each occur an odd number of times, their XOR alone does not identify either value. Choose a frequency map when occurrence counts are the real requirement.

Handle Python Signed Integers Deliberately

Python integers have arbitrary precision and negative values behave like infinite two’s-complement for bit operations. Apply an explicit width mask when the problem assumes 32 or 64 bits; avoid loops that expect a negative number to shift to zero.

Explain It in an Interview

Say: “This mask owns bit i. AND tests it, OR sets it, AND-not clears it, and XOR toggles it.” For cancellation, state the exact multiplicity contract and derive O(n) time and O(1) space.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Bit manipulation basics

x & (x - 1) drops the lowest one; XOR cancels pairs.

The problem talks about bits, or asks for an O(1)-space trick with pairs of numbers.

Trigger words

  • single number
  • xor
  • count bits
  • reverse bits
  • power of two
  • without + or -
def count_ones(n):
    count = 0
    while n:
        n &= n - 1        # clear the lowest set bit
        count += 1
    return count

def single_number(nums):
    result = 0
    for num in nums:
        result ^= num     # pairs cancel: a ^ a == 0
    return result

Spot it when

  • 'Single number', 'count bits', 'reverse bits'.
  • Add numbers without + or -.

Remember

  • n & 1 reads the lowest bit; n >> 1 drops it.
  • XOR is its own inverse: a ^ b ^ b == a.

How problems bend it

  • Counting bits for 0..n: bits[i] = bits[i >> 1] + (i & 1).
  • Reverse 32 bits: Repeat 32 times: result = (result << 1) | (n & 1); n >>= 1.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Bit Manipulation proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
XOR fold of n valuesO(n)O(n)Assumes bounded-width integers; arbitrary-size bitwise operations additionally depend on bit length.
A fixed number of mask operationsO(1)O(1)Only under a fixed-width arithmetic model.

Space

O(1) accumulator slots; large integer storage scales with bit length.

Assumptions

  • Python integers are unbounded, and negative bitwise values behave as though they have infinitely many sign bits.
  • Clearing one set bit per iteration counts set bits only for a nonnegative input; that is a different workflow from the XOR Lab.

Invariants Worth Saying Aloud

  1. A one-bit mask touches only its designated position.
  2. Setting an already set bit changes nothing; toggling it clears it.
  3. The XOR accumulator equals the XOR of the processed prefix; equal pairs cancel regardless of adjacency.

When To Use Or Avoid Bit Manipulation

Use It When

  • Represent a small finite subset or independent flags with one bit per item.
  • Use XOR cancellation only when the occurrence-parity premise matches the requested result.

Choose Another Tool When

  • Use a set or dictionary when elements have no natural bounded bit position and clarity matters more than compactness.
  • Do not apply a fixed-width complement or right-shift interpretation to Python negative integers without an explicit mask.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Using logical or when setting a bit

Python or returns an operand according to truthiness. With value 8 and mask 1 it returns 8, never setting the low bit.

Prevent it: Use bitwise | to combine individual bit positions.

Avoid

result = value or mask

Use instead

result = value | mask

Toggling when the operation says set

XOR flips a bit. If bit 3 is already set in value 8, XOR with 8 clears it to zero.

Prevent it: Use | for an idempotent set operation; reserve XOR for intentional toggling.

Avoid

result = value ^ mask

Use instead

result = value | mask

Expecting a finite-width complement from ~

~1 is -2 in Python, not the four-bit pattern 1110. The integer has no implicit four-bit width.

Prevent it: Mask the complement with (1 << width) - 1 when the contract specifies width bits.

Avoid

result = ~value

Use instead

result = (~value) & ((1 << width) - 1)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.