DSA for Interviews
Back to Advanced Patterns

Bit Manipulation

XOR tricks, bit counting, power-of-2 checks. The handful of bit operations that pop up in interview problems. FIND_VIDEO: search 'bit manipulation tricks interview' — recommended channel: NeetCode / Tushar Roy. Aim for 9 min or under.

6 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Missing Number Puzzle — Presents the challenge of finding a missing integer from 1 to a million with zero memory.
  2. Hardware Bitwise Fundamentals — Explains that bitwise operations run directly on CPU hardware in single clock cycles.
  3. Bitmask Construction — Demonstrates creating bitmasks with left shifts to set, clear, and toggle specific bits.
  4. XOR Missing Number Solution — Solves the missing number problem using XOR self-cancellation across expected and actual values.
  5. Brian Kernighan Algorithm — Introduces the n & (n - 1) operation to count set bits in iterations proportional to set bit count.
  6. Power of Two Verification — Explains the constant-time logic for determining whether an integer is a power of two.
PDF notes

Frequently asked questions

Why does XORing identical numbers always produce zero?

XOR yields 1 only when bits differ; because identical numbers share identical bits at every position, all bit comparisons evaluate to 0.

Why is Brian Kernighan's algorithm faster than standard bit checking?

It clears one set bit per step using n & (n - 1), making iteration count equal to the number of set bits rather than total bit length.

How does n & (n - 1) remove the rightmost set bit?

Subtracting 1 turns the lowest 1-bit to 0 and inverts all lower zeros to ones, leaving zero overlapping 1-bits in that lower region when ANDed.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.