Skip to main content

Theory

Basics of Bits

  • Bit: The smallest unit of data in a computer, either 0 or 1.
  • Binary Representation: Any integer can be represented in base-2. Example: 5 in binary → 101, 10 in binary → 1010.
  • Why Bit Manipulation?
    • Faster than arithmetic operations (O(1) for most operations).
    • Saves space (storing multiple states in a single integer).
    • Useful in problems involving sets, flags, XOR, AND masks.

Common Bitwise Operators

\ is actually |. The bitwise OR operators which is denote by | can’t be used inside a mdx table

Common Patterns to remember

Common Operations

1. Checking if a bit is set or not
Setting the rightmost set bit to 1
Unsetting the rightmost set bit to 1
2. Setting Kth bit to 1
3. Setting Kth bit to 0(Clearing Kth bit)
4. Toggling Kth bit
5. Counting set bits
6. Power of Two Check
7. XOR Tricks XOR Properties:
  1. a ^ a = 0
  2. a ^ 0 = a
  3. a ^ b ^ a = b (commutative and associative)
Applications: Find unique number in array where every other number occurs twice.
8. Subset generation using bits
9. Swapping Numbers Using XOR
10. Finding Rightmost Set Bit
11. Clearing Rightmost Set Bit
Tip for Interviews:
  1. Always think in terms of 0 and 1.
  2. Many problems on Leetcode: Single Number, Counting Bits, Subset Sum DP, Missing Number, Power of Two.
  3. Visualize bits as switches — “on/off” to simplify reasoning.

Algorithms

Brian Kernighan’s Algorithm

Brian Kernighan’s Algorithm is one of the most elegant and widely used bit manipulation tricks in DSA, especially for counting set bits efficiently Trick: n & (n-1) removes the rightmost set bit from n.
  • Every time you do n = n & (n-1), you remove one 1(rightmost)
  • Count how many times you can do this → number of 1s
Why does it work?
  • n - 1 flips all bits after the rightmost 1, including that 1 itself
  • ANDing it with n removes that rightmost 1
algorithm.py

Problem Set

In python, Logical AND is different from Bitwise &
Solution to All recursion solutions Github

Basics

  1. Check if the ith bit is set
  2. Check if a number is odd or not
  3. Check if a number is power of 2 or not
  4. Count the number of set bits
  5. Set/Unset the rightmost unset bit T
  6. Swap two numbers Trick
  7. Divide two numbers Trick

Medium Problems

  1. Count the number of bits to be flipped to convert A to B
  2. Single Number
  3. Power set
  4. Find xor of numbers from L to R
  5. Find the two numbers appearing odd number of times

Math problems

  1. Print Prime Factors of a Number
  2. All Divisors of a Number
  3. Sieve of Eratosthenes
  4. Find Prime Factorisation of a Number using Sieve
  5. Power(n, x)