What is Bit Manipulation?
Techniques·6 min·Python code
Bit manipulation works directly on the binary digits of integers using AND, OR, XOR, NOT and shifts. Instead of treating a number as one value, you test, set and clear single bits, which gives memory light solutions to problems about flags, pairs and powers of two.
Bits as Switches and Bitwise Operators
Think of a number as a row of switches. Integers are stored as a fixed row of bits, every one either 1 (on) or 0 (off). 32 bit integers hold 32 tiny switches, and most bit tricks ask which switches are on or flip one switch without touching the rest.
Five operators cover the job. AND (&) keeps a bit only where both inputs are 1, so it tests or clears bits. OR (|) sets a bit where either input is 1, so it turns bits on. XOR (^) sets a bit where the two differ, so it toggles, and it cancels itself, meaning a ^ a = 0 and a ^ 0 = a. NOT (~) flips every bit, and shifts (<< and >>) slide bits left or right to multiply or divide by powers of two.
CPUs handle these operations in single instructions, so they cost almost nothing. Watching the switches change step by step teaches the identities faster than memorising them.
Bit Masks for Testing Setting and Clearing Bits
Masks are integers built to isolate the bits you care about. Your workhorse is 1 << k, a single 1 at position k.
With that mask you test a bit with x & (1 << k), set it using x | (1 << k), clear it using x & ~(1 << k) and toggle it using x ^ (1 << k). Nearly every bit problem comes down to building the right mask and applying one of these four moves.
Small sets fit in a mask too. One integer can stand in for a set of items, which lets you loop over every subset and drive bitmask dynamic programming.
Bit Manipulation Patterns Interviews Ask
Single number comes first. XOR every element of an array together. Equal pairs cancel to 0, and the lone unmatched value survives in one pass with no extra memory.
Counting set bits follows. Brian Kernighan's trick n &= n - 1 clears the lowest set bit on every pass, so the loop repeats once per 1 bit. Power of two checks need one line, because powers of two hold exactly one set bit.
Two more help. Use n & -n to isolate the lowest set bit. These few identities cover most bit questions you will meet, and CodeStory's bit manipulation practice problems drill them. Compare them with a hash table approach on the same input.
Bit Manipulation Code Example in Python
def single_number(nums):
# XOR cancels equal pairs; the unique value survives
result = 0
for n in nums:
result ^= n
return result
def count_set_bits(n):
# Brian Kernighan: n & (n - 1) clears the lowest set bit
count = 0
while n:
n &= n - 1
count += 1
return count
def is_power_of_two(n):
# A power of two has exactly one set bit
return n > 0 and (n & (n - 1)) == 0
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Bit Manipulation Time and Space Complexity
| Time | O(1) for a bitwise or shift operation, O(n) to XOR across n numbers and O(set bits) for Kernighan's popcount |
|---|---|
| Space | O(1) auxiliary, since a few integer variables replace extra data structures |
Kernighan's loop finishes in a couple of passes when few bits are set and needs one pass per bit at worst, up to the word width of 32 or 64. Plain bit by bit scans cost O(word size) for every input.
When to Use Bit Manipulation
- You track a small set of on and off flags compactly, with a bitmask instead of a boolean array or hash set, including bitmask DP over subsets.
- Problems hinge on pairing, cancellation or parity. XOR finds the unique number, spots a missing or duplicated value and swaps two variables without a temp.
- You need checks tied to powers of two, like testing, setting or clearing a specific bit, or aligning to a boundary.
- Tight memory or speed limits make shifts and masks worth the effort, like embedded code, hashing and low level systems.
Mistakes to Avoid
- Trusting operator precedence. In C, Java and JavaScript, == binds tighter than &, | and ^, so x & 1 == 0 parses as x & (1 == 0). Python orders them the other way, and brackets around every bitwise test keep both readable.
- Ignoring signed shifts and width limits. Shifting negatives, or shifting past the type width, depends on the language, like Java's >> vs >>>, JavaScript coercing to 32 bits and undefined behaviour in C. Python integers have no fixed width, so ~ and shifts differ from fixed width languages.
- Using bit tricks where they do not help. Cleverness that hurts readability without improving complexity costs your team time.
Bit Manipulation FAQs
Is bit manipulation hard to learn?
Only five operators exist (AND, OR, XOR, NOT and shifts) and every one does a single clear thing. Practice goes into spotting when a problem has a bitwise shortcut and building masks fluently. Watching bits flip step by step helps more than reading definitions.
When should I use bit manipulation instead of a hash set or array?
Use bits when you track on and off flags compactly, when a problem relies on XOR pairing and cancellation or when you need quick power of two checks. For general lookups, a hash set reads more clearly. Choose bits when they cut memory or unlock the trick.
What is the time complexity of counting set bits?
Brian Kernighan's method (n &= n - 1) repeats once per set bit, so it costs O(set bits), which stays at or below the word width of 32 or 64. Naive scans of every bit cost O(word size). Both use O(1) extra space.
What does XOR do and why is it useful?
XOR outputs 1 only where two bits differ, and it cancels itself, so a ^ a = 0 and a ^ 0 = a. That finds a unique element among pairs, toggles bits, detects differences and swaps two variables without a temporary.
How do I check if a number is a power of two?
Test n > 0 and (n & (n - 1)) == 0. Powers of two hold exactly one set bit, and n & (n - 1) clears it, which leaves zero.
How do I test, set, clear and toggle a bit?
Build the mask 1 << k, then use x & mask to test, x | mask to set, x & ~mask to clear and x ^ mask to toggle.
How do I practise bit manipulation on CodeStory?
Write the three patterns above yourself in the browser IDE, then try CodeStory's bit manipulation practice problems.
Related Guides
Guides are step one. In a CodeStory batch you code bit tricks yourself, then explain every mask in a scored mock round.
Talk to a Mentor