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 tableCommon Patterns to remember
Common Operations
1. Checking if a bit is set or nota ^ a = 0a ^ 0 = aa ^ b ^ a = b(commutative and associative)
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
n - 1flips all bits after the rightmost 1, including that 1 itself- ANDing it with n removes that rightmost 1
algorithm.py
Problem Set
Solution to All recursion solutions Github
Basics
- Check if the ith bit is set
- Check if a number is odd or not
- Check if a number is power of 2 or not
- Count the number of set bits
- Set/Unset the rightmost unset bit T
- Swap two numbers Trick
- Divide two numbers Trick
Medium Problems
- Count the number of bits to be flipped to convert A to B
- Single Number
- Power set
- Find xor of numbers from L to R
- Find the two numbers appearing odd number of times