Math & Bits 101
Intermediate · 4 chapters · 8 min read · Use XOR, powers of two and number tricks to solve problems in a few lines.
Practise this in the app All guides
When maths and bits are the answer
Numbers have structure
Some interview problems look like they need a data structure but really need a small mathematical observation: XOR cancels pairs, a power can be computed by repeated squaring, a line through two points has a slope you can store as a reduced fraction. Recognising these saves you from long, fragile code.
Binary in one minute
Every integer is a sum of powers of two. 13 is 1101 in binary: 8 + 4 + 1. The bit operators work on these digits directly:
a & b(AND): 1 only where both bits are 1, so12 & 10 == 8.a | b(OR): 1 where either bit is 1, so12 | 10 == 14.a ^ b(XOR): 1 where the bits differ, so12 ^ 10 == 6.~a(NOT): flips every bit; in Python~0 == -1.a << k: multiplies by 2^k, so3 << 2 == 12.a >> k: floor-divides by 2^k, so13 >> 1 == 6.
Signals in a problem statement
- "Every element appears twice except one" — XOR.
- "Without using extra space" on counting or uniqueness problems.
- "Count the 1 bits", "power of two", "reverse bits".
- "Compute x to the power n" for large
n, or "modulo 10⁹ + 7". - "Points on a line", "GCD", "LCM", "primes up to n".
- "All subsets" of a small set (n ≤ 20) — bitmasks.
Key XOR facts
x ^ x == 0, x ^ 0 == x, and XOR is commutative and associative. So XOR-ing a whole list cancels every value that appears an even number of times, leaving the odd one out. That one fact solves a surprising number of questions in O(n) time and O(1) space.
Core patterns with templates
1. XOR cancels pairs
def single_number(nums):
x = 0
for v in nums:
x ^= v
return x
2. Bit tricks you should know
def is_power_of_two(n):
return n > 0 and n & (n - 1) == 0
def count_ones(n):
c = 0
while n:
n &= n - 1 # drop the lowest set bit
c += 1
return c
3. Reuse smaller answers (bits DP)
i >> 1 is i without its last bit, so the count of ones in i is the count for i >> 1 plus the last bit.
def count_bits(n):
ans = [0] * (n + 1)
for i in range(1, n + 1):
ans[i] = ans[i >> 1] + (i & 1)
return ans
4. Fast power by squaring
def power(x, n):
if n < 0:
x, n = 1 / x, -n
result = 1.0
while n:
if n & 1:
result *= x
x *= x
n >>= 1
return result
Example: x^13 with 13 = 1101₂ multiplies x^8 · x^4 · x^1, needing about four squarings instead of twelve multiplications.
5. Exact slopes with GCD
For "maximum points on a line", fix one point and count the others by the slope to it. Store the slope as a reduced pair, never as a float.
from math import gcd
from collections import Counter
def max_points(points):
best = 0
for i, (x1, y1) in enumerate(points):
slopes = Counter()
for x2, y2 in points[i + 1:]:
dx, dy = x2 - x1, y2 - y1
g = gcd(dx, dy)
dx, dy = dx // g, dy // g
if dx < 0 or (dx == 0 and dy < 0):
dx, dy = -dx, -dy
slopes[(dx, dy)] += 1
best = max(best, 1 + max(slopes.values(), default=0))
return best
The sign normalisation makes (1, -2) and (-1, 2) the same slope.
Complexity, mistakes and edge cases
Complexity
| Task | Time | Space |
|---|---|---|
| XOR of a list | O(n) | O(1) |
| Count bits of one number | O(number of set bits) | O(1) |
| Bits for 0..n | O(n) | O(n) output |
| Fast power | O(log n) | O(1) |
gcd(a, b) | O(log min(a, b)) | O(1) |
| Points on a line | O(n²) | O(n) |
Common mistakes
- Operator precedence. In Python,
&binds tighter than==, son & (n - 1) == 0happens to work, but in C++ and Java==binds tighter than&and the same expression is a bug. Add brackets:(n & (n - 1)) == 0. - Negative numbers. Python integers are unbounded, so
~xand right shifts of negatives behave differently from 32-bit languages. If a problem expects 32-bit behaviour, mask with& 0xFFFFFFFF. - Negative exponents.
power(2, -2)must be 0.25. Also handlen = -2³¹in fixed-width languages, where negating overflows. - Floating-point slopes.
dy / dxloses precision and divides by zero on vertical lines; use reduced integer pairs. - Duplicate points. If the problem allows them, count them separately and add them to every slope from that point.
- Forgetting the modulo at every multiplication when the answer must be taken modulo 10⁹ + 7; in Python it will not overflow, but it will become slow.
Edge cases
n = 0 and n = 1 for bit counts, x = 0 with a negative exponent, a single point or two points (always on one line), vertical and horizontal lines, all points identical, and the minimum and maximum 32-bit integers.
Useful identities
x & -x isolates the lowest set bit. x | (1 << k) sets bit k; x & ~(1 << k) clears it; (x >> k) & 1 reads it. These four lines cover most bitmask code you will need.
Variations and practise
How interviewers twist it
- Two numbers appear once, the rest twice. XOR everything to get
a ^ b, take any set bit of it (d & -d), and split the numbers into two groups by that bit; XOR each group separately. - One number appears once, the rest three times. Count each bit position modulo 3, or use the
ones/twosstate trick. - Missing number from 0..n. XOR all indices and all values, or subtract the sum from
n(n + 1) / 2. - Subsets with bitmasks. For
maskinrange(1 << n), elementiis included whenmask >> i & 1. - Modular exponentiation. Python's built-in
pow(base, exp, mod)does fast power modulomodin one call. - Sieve of Eratosthenes for counting primes below n in O(n log log n).
- Digit manipulation. Reverse an integer, check a palindrome number, or add binary strings, all by working with
% 10or% 2and carrying.
How to explain it
Name the property you rely on: "XOR cancels equal pairs, so only the single number survives", or "squaring halves the exponent each step". A short, precise sentence makes even a three-line solution feel well understood.
Practise
The problems below cover the XOR trick, counting bits with a small recurrence, fast exponentiation with negative powers, and counting points on a line with exact slopes. Try each one first with the obvious approach, then rewrite it using the property from this card.
Practise
Easy
- 2806. Single Number
- 2807. Counting Bits
- 2812. Count the Lit Bits
- 2816. Exact Power of Four
- 2817. Is It a Clean Power of Two
- 2818. Exact Power of Three
- 2819. Mirror a 16-bit Value
- 2820. Bit Disagreements Between Two Numbers
- 2821. Flip Every Meaningful Bit
- 2822. Do the Bits Alternate
- 2823. The Missing Badge Number
- 2824. The Extra Letter
- 2825. A Number That Reads the Same Both Ways
- 2826. Reverse Digits Within 32 Bits
- 2827. Increment a Digit List
- 2828. Sum Two Binary Strings
- 2829. Sum Two Huge Decimal Strings
- 2830. Chime and Bell
- 2831. Primes Below a Limit
- 2832. Only 2, 3 and 5 Inside
- 2833. Equal to Its Proper Divisors
- 2834. Numbers Divisible by Their Own Digits
- 2835. Digit Product Minus Digit Sum
- 2836. How Many Have an Even Digit Count
- 2837. Spreadsheet Column Label to Index
- 2838. Index to Spreadsheet Column Label
- 2839. Zeros at the End of n Factorial
- 2840. GCD of the Smallest and Largest
- 2841. Write a Number in Base 7
- 2842. Hexadecimal Including Negatives
- 2843. Value of a Roman Numeral
- 2844. Complete Rows of a Staircase
- 2845. Three Consecutive Integers Summing to n
- 2846. Area Covered by Two Rectangles
- 2847. Do All Points Lie on One Line
- 2848. One Row of Binomial Coefficients
- 2849. Sign of a Big Product
- 2850. Largest Product of Three Values
- 2851. Least Common Multiple of a List
- 2852. Shared Divisors of Two Numbers
- 2853. Values With a Prime Number of Set Bits
- 2854. Order by Number of Set Bits
- 2855. Recover a List From Neighbour XORs
- 2856. Widest Gap Between Set Bits
- 2857. One Block of Ones Followed by Zeros
- 2858. Day Number Within the Year
- 2859. Days Between Two Calendar Dates
- 2860. Refill Swaps for Empty Bottles
- 2861. Largest Valid Triangle Perimeter
- 2862. Largest Triangle From Given Points
- 2863. Equal to Its Powered Digits
- 2864. Gray Code of a Single Value
- 2865. Swap Each Neighbouring Bit Pair
- 2866. Steps to Reduce a Number to Zero
- 2867. Binary Prefixes Divisible by k
- 2868. Tax Under Progressive Brackets
- 2869. Sum of Distinct Powers of Three
- 2870. The Gap in an Arithmetic Run
- 2898. The Doubled and the Absent Value
- 2907. Break a Number Into Prime Powers
- 2962. Primes on Prime Seats
Medium
- 2808. Pow(x, n)
- 2809. Single Number II
- 2813. Integer Division With Shifts Only
- 2814. Add Two Integers Without Plus or Minus
- 2815. AND of Every Number in a Range
- 2871. Strongest XOR Pair
- 2872. Two Values Without a Partner
- 2873. Walk All n-bit Codes Changing One Bit
- 2874. Total Bit Disagreements Over All Pairs
- 2875. Longest Pair of Words With No Shared Letters
- 2876. Fewest Flips So a OR b Equals c
- 2877. Range XOR Queries
- 2878. Triplets Whose Two Halves XOR Equal
- 2879. Rebuild a Permutation From Neighbour XORs
- 2880. Longest Run Achieving the Maximum AND
- 2881. Shortest Window Reaching the Best OR From Each Start
- 2882. Closest XOR Partner With a Fixed Bit Count
- 2883. Glue Binary Numbers 1..n
- 2884. Best XOR Answers While Removing From the End
- 2885. Longest Window With Pairwise Zero AND
- 2886. Symbol in a Doubling Pattern
- 2887. k-th Character of the Invert-and-Mirror String
- 2888. Biggest Group With a Non-Zero AND
- 2889. Validate a Byte Stream as UTF-8
- 2890. Fewest Steps to One With Halving or Plus/Minus One
- 2891. XOR of All Cross-Pair XORs
- 2892. XOR Over All Pairwise ANDs
- 2893. Smallest Last Value of a Strictly Rising AND-Locked List
- 2895. OR of Every Subsequence Sum
- 2896. Best OR After Doubling One Value k Times
- 2897. One Value Repeats in 1..n
- 2899. Root-to-Leaf Paths That Can Be Rearranged Into Palindromes
- 2900. Substrings With At Most One Odd Letter
- 2901. Longest Concatenation With All-Distinct Letters
- 2902. Sum of XORs of All Subarrays
- 2903. Total Set Bits From 1 to n
- 2904. Next Larger Value With the Same Bit Count
- 2905. Does a Bit String Contain Every k-bit Code
- 2906. Primes in a Wide Window
- 2908. Distinct Prime Factors Across a List
- 2909. Power Mod With a Digit-List Exponent
- 2910. Modular Inverse Under a Prime
- 2911. n Choose r Modulo a Large Prime
- 2912. Solve ax + by = c in Integers
- 2913. Measure Exact Liters With Two Jugs
- 2914. Number Matching Several Remainders
- 2915. Sum of Divisor Counts Up to n
- 2916. Count Coprimes Up to n
- 2917. Fraction as a Repeating Decimal String
- 2918. Add a Chain of Fractions
- 2919. Multiply Two Huge Decimal Strings
- 2920. The n-th Digit of the Counting Stream
- 2921. k-th Arrangement of 1..n
- 2922. Count Values With No Repeated Digit Below 10^n
- 2923. Split n Into Parts With Maximum Product
- 2924. Shortest All-Ones Number Divisible by k
- 2925. Ways to Write n as Consecutive Positive Sums
- 2926. Bulbs Left On After n Toggle Rounds
- 2927. Last Survivor of Alternating Sweeps
- 2928. Last One Standing in a Circle
- 2929. n-th Number With Only 2, 3 and 5 as Factors
- 2930. Fewest Squares Summing to n
- 2931. Is n a Sum of Two Squares
- 2932. Numbers That Change When Turned Upside Down
- 2933. All n-Digit Numbers Symmetric Under Half-Turn
- 2934. Write a Number in Base Minus Two
- 2935. Next Bigger Number From the Same Digits
- 2936. Biggest Number After One Digit Swap
- 2937. Largest Value Up to n With Non-Decreasing Digits
- 2938. Write a Value as a Roman Numeral
- 2939. Equalize With Single-Step Moves
- 2940. Do Four Points Form a Square
- 2941. Smallest Axis-Aligned Rectangle From Points
- 2942. Grid Points Covered by Circles
- 2943. Does a Circle Touch a Rectangle
- 2944. Where Does the Laser Exit
- 2945. Is the Polygon Convex
- 2946. Lattice Points Strictly Inside a Polygon
- 2947. Ways to Roll a Target With n Dice
- 2948. Chance of Stopping at or Below n
- 2949. Two Pots Emptying Randomly
- 2950. Knight Staying on the Board
- 2951. Arrangements With Nobody in Their Own Seat
- 2952. Up-Down Walks That Never Dip Below Start
- 2953. Trailing Zeros of n! in Base b
- 2954. How Many n Have Exactly k Zeros in n!
- 2955. Closest Factor Pair of n + 1 or n + 2
- 2956. Smallest Number Whose Digits Multiply to n
- 2957. Total of Divisors for Numbers With Exactly Four
- 2958. Subarrays Whose GCD Is k
- 2959. Spread a One Using Neighbour GCDs
- 2960. Pairs Whose Sum Is a Multiple of k
- 2961. Nearest Pair of Primes in a Range
- 2963. Digit Strings With Position Rules
- 2964. Fibonacci Remainder via Its Cycle
- 2965. Values Up to n With Digit Sum Divisible by k
- 2966. Values Up to n Built From Allowed Digits
- 2967. Values in a Range With Exactly k Set Bits
- 2968. Reach a Point With Growing Steps
- 2969. Double or Decrement to Reach a Target
- 2970. Copy-All and Paste to Reach n Characters
- 2971. Best Rotation Weighted Sum
- 2972. Subarrays With an Odd Total
- 2973. Substrings Made Only of 1s
- 2974. Smallest Gap Between Clock Times
- 2975. Does the Robot Stay Within a Circle
- 2976. Fewest Tasters for Poisoned Barrels
- 2977. Who Wins Multi-Pile Take-Away
- 2978. Who Runs Out of Chalk
- 2979. Ways Ants on a Polygon Collide
- 2980. Distance Totals in a Sorted List
- 2981. Smallest Prime Palindrome at or Above n
- 2982. Symmetric About a Vertical Line
- 2983. Solve a One-Variable Linear Equation
- 2984. Fewest Fibonacci Terms Summing to k
- 2985. Values Up to m Coprime With n
- 2986. Light States After Button Presses
- 2987. First to Reach the Total Picking Unused Numbers
- 2988. Path to a Label in a Zigzag-Numbered Tree
- 2989. Chance a Gambler Reaches the Goal
- 3015. Smallest Tilted Rectangle From Points
- 3040. Avoid a Sum Divisible by Three
- 3041. k-th Smallest Fraction From Sorted Primes
- 3044. Cycle Lengths in an Infinite Binary Heap
- 3046. Perfect Powers Up to n
Hard
- 2810. Max Points on a Line
- 2811. Number of Digit One
- 2894. Best XOR With a Cap Per Query
- 2990. Largest XOR of Any Subset
- 2991. Pairs Whose XOR Lands in a Range
- 2992. k-th Smallest Distinct Subset XOR
- 2993. Pair Two Lists to Minimise the XOR Total
- 2994. Undo a Number With Restricted Bit Flips
- 2995. Pairs Whose AND Is Zero
- 2996. Words Solvable for Each Puzzle
- 2997. Split Powers of Two to Reach a Sum
- 2998. Spell a Number in English Words
- 2999. Closest Palindrome to a Number String
- 3000. Values Up to n With All-Distinct Digits
- 3001. No Two Neighbouring Ones Up to n
- 3002. Neighbour-Digit Numbers in a Huge Range
- 3003. Palindromes Whose Square Root Is a Palindrome
- 3004. Grow a Pair Back to Its Start
- 3005. Binomial Coefficient Modulo a Small Prime
- 3006. Arrays of Length n Multiplying to k
- 3007. Distinct Rearrangements of Every Word
- 3008. Insert Orders Producing the Same Search Tree
- 3009. Arrangements With Exactly k Out-of-Order Pairs
- 3010. Fair Split of Coloured Balls
- 3011. Fence Around All Trees
- 3012. Most Points in a Viewing Angle
- 3013. Do Tiles Form One Exact Rectangle
- 3014. Total Area Under Overlapping Rectangles
- 3016. Does the Spiral Walk Cross Itself
- 3017. Point Minimising Total Distance
- 3018. Most Darts in One Circle
- 3019. Are Two Repeating Decimals Equal
- 3020. k-th Amount From Single-Coin Payouts
- 3021. Pair Up for the Best Weighted GCDs
- 3022. Distinct GCDs of Subsequences
- 3023. Sort Boxes by Swapping Shared Factors
- 3024. Earliest Clean Split
- 3025. Count the Coprime Pairs
- 3026. Square-Free Product Subsets
- 3027. Fewest Drops to Find the Critical Floor
- 3028. Best AND Score in a Two-Per-Slot Rack
- 3029. Smallest OR After Neighbour Merges
- 3030. Pairs Whose OR and AND Bit Counts Reach k
- 3031. Ways to Split n Into Unordered Parts
- 3032. k-th Term of a Linear Recurrence
- 3033. Fewest Days to Finish n Oranges
- 3034. XOR of a Range Skipping One Residue
- 3035. Smallest Multiple of d With Digit Sum s
- 3036. Pairs With a Product Divisible by k
- 3037. Product of a Range in Short Form
- 3038. Fewest Operators to Build a Target From x
- 3039. Split-or-Take Pile Game Winner
- 3042. Total of Pairwise Floor Quotients
- 3043. Reachable With Doubling and Subtracting Moves
- 3045. Dice Roll Sequences With Coprime Neighbours
- 3047. Total Spread Over All Subsequences