Bit Manipulation & Math
Reach for it when the problem says
- "Without extra space"
- single number
- powers of two
- digits
- Solved
- 0/32Solved
- Problems
- 32Problems
- Variants
- 6Variants
Problems
6 variantsXOR cancellation
0 of 4 solved- Single NumberUp nextEssentialsSprintDeep diveEasyDecode Single Number
- Missing NumberEasyDecode Missing Number
- Single Number IIIMediumDecode Single Number III
- Maximum XOR of Two Numbers in an ArrayMediumDecode Maximum XOR of Two Numbers in an Array
Counting set bits
0 of 6 solved- Number of 1 BitsSprintDeep diveEasyDecode Number of 1 Bits
- Counting BitsEssentialsDeep diveEasyDecode Counting Bits
- Hamming DistanceEasyDecode Hamming Distance
- Total Hamming DistanceMediumDecode Total Hamming Distance
- Single Number IISprintDeep diveMediumDecode Single Number II
- Minimum Flips to Make a OR b Equal to cEssentialsDeep diveMediumDecode Minimum Flips to Make a OR b Equal to c
Masks and shifts
0 of 6 solved- Reverse BitsSprintDeep diveEasyDecode Reverse Bits
- Power of TwoEasyDecode Power of Two
- Power of FourEasyDecode Power of Four
- Complement of Base 10 IntegerEasyDecode Complement of Base 10 Integer
- Bitwise AND of Numbers RangeSprintDeep diveMediumDecode Bitwise AND of Numbers Range
- Game of LifeSprintDeep diveMediumDecode Game of Life
Arithmetic by hand
0 of 6 solved- Add BinarySprintDeep diveEasyDecode Add Binary
- Plus OneSprintDeep diveEasyDecode Plus One
- Sum of Two IntegersDeep diveMediumDecode Sum of Two Integers
- Multiply StringsDeep diveMediumDecode Multiply Strings
- Divide Two IntegersMediumDecode Divide Two Integers
- Pow(x, n)SprintDeep diveMediumDecode Pow(x, n)
Digit manipulation
0 of 6 solved- Palindrome NumberSprintDeep diveEasyDecode Palindrome Number
- Happy NumberSprintDeep diveEasyDecode Happy Number
- Excel Sheet Column NumberEasyDecode Excel Sheet Column Number
- Roman to IntegerSprintDeep diveEasyDecode Roman to Integer
- Reverse IntegerMediumDecode Reverse Integer
- Integer to RomanSprintDeep diveMediumDecode Integer to Roman
Number theory
0 of 4 solved- Greatest Common Divisor of StringsEssentialsDeep diveEasyDecode Greatest Common Divisor of Strings
- Factorial Trailing ZeroesSprintDeep diveMediumDecode Factorial Trailing Zeroes
- Count PrimesMediumDecode Count Primes
- Max Points on a LineSprintDeep diveHardDecode Max Points on a Line
Pattern guide
Bit and math problems look like a grab bag, but they share one move: instead of building a data structure, you use a property of numbers to get the answer in O(1) extra space. Interviewers like them because the brute force is easy (a hash map, a string conversion, a big loop) and the follow-up "can you do it without extra space?" separates people who know the tools from people who do not.
What it is
Every integer is stored as bits. Operators like & (AND), | (OR), ^ (XOR), ~ (NOT), << and >> (shifts) act on all bits at once, so one operation does 32 tiny comparisons in a single step. Math problems use the same idea with decimal digits (% 10 and // 10) or with facts like "a trailing zero needs a factor of 5".
Here is the most famous trick. XOR outputs 1 where two bits differ, so x ^ x = 0 and x ^ 0 = x. XOR a whole list together and every pair cancels.
Start with acc = 0. XOR in 4 (binary 100): acc is now 4.
Order did not matter, and no memory was used beyond one integer. That is the flavour of the whole category.
Python integers vs JavaScript numbers
This matters in almost every bit problem, so learn it once.
| Python | JavaScript / TypeScript | |
|---|---|---|
| Integer size | Unbounded: 2 ** 100 is exact | Numbers are 64-bit floats, exact up to 2^53 - 1 |
| Bitwise operators | Work on the full integer, any size | Convert to a signed 32-bit integer first |
1 << 31 | 2147483648 | -2147483648 (the sign bit) |
| Negative numbers | Act like infinite two's complement: -1 is "all ones forever" | Exactly 32 bits of two's complement |
| Unsigned result | Always non-negative if you never go negative | Use x >>> 0 to reread the 32 bits as unsigned |
| Unsigned right shift | Not needed | >>> fills with zeros; >> copies the sign bit |
Two consequences come up again and again. In JavaScript, anything that sets bit 31 turns negative, so problems with unsigned 32-bit answers (Reverse Bits) need >>> 0, and values like 2^31 (from negating -2^31) cannot go through & or >> safely. In Python, nothing ever overflows, so problems that rely on 32-bit wraparound (Sum of Two Integers) need a manual mask, & 0xFFFFFFFF, and a final conversion back to a signed value.
What does this print?
console.log(1 << 31, (1 << 31) >>> 0);
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "appears twice except one", "appears three times" | XOR cancellation, or counting each bit modulo k |
| "without extra space", "O(1) extra space" | A running integer instead of a hash map |
| "power of two", "power of four" | One set bit: n & (n - 1) == 0, plus a mask |
| "number of 1 bits", "Hamming distance" | XOR to mark differences, then count set bits |
| "unsigned 32-bit", "reverse the bits" | Shifts and masks, with >>> 0 in JavaScript |
"without using +", "without *, / or %" | Rebuild arithmetic from XOR, AND, shifts and doubling |
| "digits", "reverse the integer", "palindrome number" | Pop with % 10, push with * 10 |
| "stored as a string", "too large for an integer" | Schoolbook arithmetic with a carry |
| "primes", "factorial", "greatest common divisor" | Number theory: sieve, factor counting, Euclid |
Constraint clues
| Constraint | What it suggests |
|---|---|
-2^31 <= x <= 2^31 - 1 | 32-bit thinking: overflow checks, the sign bit, at most 31 or 32 loop steps |
0 <= n <= 2^32 - 1 | Unsigned values above JavaScript's signed range: use >>> and >>> 0 |
nums.length <= 10^5 with "O(1) space" | One linear pass with an accumulator, not sorting |
length <= 10^4 for a number given as a string | Digit-by-digit arithmetic, O(n) |
n <= 5 * 10^6 with "primes" | A sieve over an array of size n |
A range like [left, right] up to 2^31 | Do not iterate; find a property of the endpoints |
Input and output shape clues
- A single integer in, a single integer or boolean out: almost always bits or digits. Ask "what does this look like in binary?"
- An array where everything is paired except a few: XOR, or per-bit counts.
- Numbers as strings or digit arrays: arithmetic by hand, right to left with a carry.
- "Sum over all pairs" of a bitwise quantity: handle one bit position at a time and count pairs with multiplication.
Looks like it but isn't
- Arrays and hashing. A count map solves Single Number instantly. It is the right first answer, but when the prompt says O(1) space, it is a decoy.
- Two pointers on a sorted copy. Sorting groups duplicates, but costs O(n log n) and rarely matches the intended bound.
- Greedy or DP for Integer to Roman. It smells like coin change, but the Roman table is built so that "largest that fits" is always right. No table of subproblems is needed.
- Binary search for Divide Two Integers. Checking a guess needs multiplication, which is banned. Doubling the divisor is the bit-level version of the same idea.
The sub-patterns
XOR cancellation
When it applies: things come in pairs and you need what is left over, or you need two numbers whose XOR is something. The tools are x ^ x = 0, x ^ 0 = x, order not mattering, and a ^ b = c meaning a ^ c = b.
When two values are left over (Single Number III), the total XOR is a ^ b. Its lowest set bit, x & -x, is a position where a and b differ, so it splits the array into two groups that each hold one single.
XOR everything. The pairs cancel, leaving 3 ^ 5 = 6, binary 110.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space. Best-known problems: Single Number, Missing Number, Single Number III, Maximum XOR of Two Numbers in an Array.
Counting set bits
When it applies: the answer is a count of 1 bits, or you must reason about each bit position separately (Hamming distances, values that appear three times, OR equations).
The core tool is n & (n - 1), which clears the lowest set bit. Subtracting 1 flips the lowest 1 to 0 and every 0 below it to 1, and the AND keeps only the bits that did not change.
n = 44 is 101100. Its lowest set bit is bit 2.
When you need per-position reasoning, loop over the 32 positions and count. For values that appear three times, a bit whose count is not divisible by 3 belongs to the single value.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(number of set bits) for one popcount; O(32 · n) for per-bit counting. Best-known problems: Number of 1 Bits, Counting Bits, Total Hamming Distance, Single Number II.
Masks and shifts
When it applies: you need to test, set, clear, flip or move particular bits. A mask is a number whose 1 bits mark the positions you care about.
| Goal | Expression |
|---|---|
Is bit i set? | (n >> i) & 1 |
Set bit i | n OR (1 << i) |
Clear bit i | n & ~(1 << i) |
Flip bit i | n ^ (1 << i) |
| Lowest set bit only | n & -n |
| Exactly one bit set? | n > 0 and n & (n - 1) == 0 |
| Bits at even positions | 0x55555555 (0101...0101) |
n = 10 is 1010. We want to flip only these four bits; ~n would also flip the endless leading zeros and go negative.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(1) for fixed-width tricks, O(32) for loops over all bits. Best-known problems: Reverse Bits, Power of Two, Power of Four, Bitwise AND of Numbers Range.
What does this print?
print(5 & 3, 5 | 3, 5 ^ 3, 5 << 1, 5 >> 1)
Arithmetic by hand
When it applies: an operator is banned, or the numbers are too big for any integer type, so you rebuild arithmetic the way you learned it on paper.
For addition with no +: the sum digit of a column is XOR and the carry is AND. So a ^ b adds everything without carrying, and (a & b) << 1 is the carries moved one column left. Repeat until there are no carries.
a = 5 (0101), b = 3 (0011).
For strings or digit arrays, walk from the right with a carry: total = carry + digits, write total % base, carry total // base. For multiplication, digit i times digit j lands at position i + j + 1. For division and powers, use doubling: subtract the biggest doubled divisor that fits, or square the base and halve the exponent.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(32) for bitwise addition, O(log n) for doubling and fast power, O(n) or O(m · n) for string arithmetic. Best-known problems: Sum of Two Integers, Add Binary, Plus One, Multiply Strings, Pow(x, n).
Put the steps of bitwise addition in Python in order.
- Tap the steps below in the right order.
Digit manipulation
When it applies: the problem talks about decimal digits, symbols with values (Roman numerals), or positional systems (spreadsheet columns). Two moves cover nearly everything:
- Pop the last digit:
digit = x % 10, thenx = x // 10. - Push a digit on the right:
result = result * 10 + digit.
Popping from one number and pushing onto another reverses it. Changing 10 to 26 reads spreadsheet columns.
Start with x = 123, result = 0.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(number of digits), which is O(log n). Best-known problems: Reverse Integer, Palindrome Number, Happy Number, Roman to Integer.
Number theory
When it applies: primes, divisibility, factorials, or greatest common divisors. The answer comes from a known fact, so the work is recognising which fact.
- Sieve of Eratosthenes: to find all primes below
n, cross out multiples of each prime, starting fromp * p. - Counting prime factors: trailing zeros of
n!are the 5s in it,n // 5 + n // 25 + .... - Euclid's gcd:
gcd(a, b) = gcd(b, a % b), ending whenbis 0.
Every number from 2 to 19 starts marked as prime.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: the sieve is O(n log log n) time and O(n) space; Euclid is O(log min(a, b)); factor counting is O(log n). Best-known problems: Count Primes, Factorial Trailing Zeroes, Greatest Common Divisor of Strings.
Decision checklist
Ask in this order: is there a pairing to cancel? Is the answer about which bits are set? Do I need to touch specific positions? Is an operator banned or is the number too big? Is it about decimal digits? Is it a fact about primes or divisors?
Match each problem to its sub-pattern.
Traps
- JavaScript's sign bit.
1 << 31is negative, and>>copies the sign bit in. For unsigned answers, finish with>>> 0and shift with>>>. Never push values of2^31or more through&,|or>>; use%andMath.floor(n / 2)instead (Pow(x, n), Divide Two Integers). - Python's missing overflow. Problems that assume 32-bit wraparound loop forever without
& 0xFFFFFFFF(Sum of Two Integers with-1 + 1). When you build a 32-bit value bit by bit, convert bit 31 back to a sign yourself (Single Number II). - Precedence. In Python,
&binds tighter than==, son & (n - 1) == 0is fine. In JavaScript,===binds tighter than&, so you must write(n & (n - 1)) === 0. - Zero and negatives.
0 & (0 - 1)is 0, so the power-of-two test needsn > 0. The complement of 0 is 1, not 0. - Stopping too early. Reverse Bits must run 32 times even when
nhits 0, because leading zeros become trailing zeros. - Overflow checks after the fact. In Reverse Integer the check must happen before
result * 10 + digit. - Truncation vs floor.
-7 / 2truncated toward zero is-3, but Python's-7 // 2is-4. Work on absolute values and apply the sign at the end.
Always test: 0, 1, a negative number, the smallest and largest 32-bit values (-2147483648, 2147483647), a power of two, and an all-ones value.
get_sum(-1, 1). Why?How to talk it through
- XOR (^)
- Outputs 1 where two bits differ.
x ^ x = 0andx ^ 0 = x, so pairs cancel. - n & (n - 1)
- Clears the lowest set bit of
n. It is 0 exactly whennhas at most one set bit. - Two's complement
- How negative integers are stored:
-xis~x + 1. It makesx & -xisolate the lowest set bit. - Mask
- A number whose 1 bits mark the positions you want to test, keep or flip, such as
0xFFFFFFFFor0x55555555. - >>> 0
- JavaScript idiom that rereads a 32-bit value as unsigned, turning
-2147483648into2147483648. - Sieve of Eratosthenes
- Finds all primes below n by crossing out multiples of each prime, starting at its square.