Skip to content

Lesson 37 of 40Strings, math and design

Math and Combinatorics for Interviews

GCD, modular arithmetic, fast powers, primes, counting and fair randomness: the small set of math that interview problems actually use.

22 min read0/5 questions

A ticketing service shows "1 in 2,300 chance" odds for a prize draw, and a bug report says some customers win far more often than others. A billing job computes a number of combinations that overflows a 64-bit integer in the Java service but not in the Python prototype. A test suite fails only on negative account balances because two services disagree about what -7 % 3 is. None of this needs a maths degree. It needs about ten facts, used precisely. This lesson covers those facts: the ones that show up in interview problems and in the code review comments you will write later.

GCD and LCM: Euclid in three lines

The greatest common divisor of two numbers is the largest number that divides both. Euclid's observation is that gcd(a, b) == gcd(b, a % b): anything that divides a and b also divides the remainder a - q*b, and the other way round. The larger number at least halves every two steps, so the loop runs O(log min(a, b)) times.

The least common multiple follows from it: lcm(a, b) = a * b / gcd(a, b). Divide before you multiply (a // gcd * b) so the intermediate value stays small. In other languages that is the difference between correct and overflowed.

Python has both built in: math.gcd and math.lcm (3.9+), and both take any number of arguments. In an interview, use them unless asked to write Euclid, then write it in one loop.

Where GCD hides in interview problems:

  • Greatest Common Divisor of Strings. If s + t != t + s, the two strings share no repeating unit at all. Otherwise the answer is the prefix of length gcd(len(s), len(t)).
  • Water and Jug. With jugs of x and y litres, the amounts you can measure are exactly the multiples of gcd(x, y) up to x + y. That is Bezout's identity, and it turns a BFS problem into one line.
  • Fractions. Reduce p/q by dividing both by their GCD, which is how you use a fraction as a hash key (Max Points on a Line uses the slope dy/dx reduced this way, with the sign normalised).
Python
import math def gcd(a, b): while b: a, b = b, a % b # gcd(a, b) == gcd(b, a mod b) return abs(a) def lcm(a, b): return a // gcd(a, b) * b # divide first to keep the number small def gcd_of_strings(s, t): if s + t != t + s: # no common repeating unit at all return "" return s[:gcd(len(s), len(t))] def can_measure(x, y, target): """Water and Jug: reachable amounts are exactly the multiples of gcd(x, y).""" if target > x + y: return False return target % gcd(x, y) == 0 assert gcd(48, 18) == 6 == math.gcd(48, 18)assert gcd(17, 5) == 1assert gcd(0, 9) == 9assert lcm(4, 6) == 12 == math.lcm(4, 6)assert gcd_of_strings("ABCABC", "ABC") == "ABC"assert gcd_of_strings("ABABAB", "ABAB") == "AB"assert gcd_of_strings("LEET", "CODE") == ""assert can_measure(3, 5, 4) is Trueassert can_measure(2, 6, 5) is Falseprint(gcd(48, 18), lcm(4, 6), gcd_of_strings("ABABAB", "ABAB"))
Output
Press Run (⌘ Enter) to see what happens.

Division and remainder with negative numbers

This is the one that breaks real systems, because every language agrees on positive numbers and quietly disagrees on negative ones.

  • Python floors. -7 // 2 is -4 (rounded toward minus infinity), and % takes the sign of the divisor, so -7 % 3 is 2. The pair always satisfies q * d + r == x.
  • JavaScript (and Java, C, C++, Go) truncates toward zero. Math.trunc(-7 / 2) is -3, and % takes the sign of the dividend, so -7 % 3 is -1.

Neither is wrong. They are two consistent conventions. The bug comes from carrying a habit from one language to the other: using x % k as a bucket or array index in JavaScript gives you negative indices, and a hash map with -1 and 2 as different keys for the same remainder. You saw this exact failure in Prefix Sums and Difference Arrays. The fix is the same everywhere: ((x % m) + m) % m.

Python
print(-7 // 2, -7 % 3, 7 % -3)print(int(-7 / 2)) # truncate toward zero, like JS Math.truncimport mathprint(math.fmod(-7, 3)) # C-style remainder: sign of the dividendq, r = divmod(-7, 3)assert q * 3 + r == -7print(q, r)
Output
Press Run (⌘ Enter) to see what happens.
JavaScript
console.log(Math.floor(-7 / 2), Math.trunc(-7 / 2), -7 % 3, 7 % -3);const mod = (x, m) => ((x % m) + m) % m; // always in [0, m)console.log(mod(-7, 3));console.log((-7 / 2) | 0); // truncates, but only safe for 32-bit values
Output
Press Run (⌘ Enter) to see what happens.

Two more traps in the same family. In Python, int(a / b) goes through a float, so it loses precision past 2^53; use // for integers, or -(-a // b) for ceiling division. In JavaScript, x | 0 truncates but also squashes the value to 32 bits, as you saw in Bit Manipulation.

Predict the outputPython

What does this print?

print(-7 % 3, -7 // 2)
Need a nudge? Hints walk you through it.

Modular arithmetic: why 10^9 + 7

When an answer would be astronomically large (the number of paths, arrangements or subsequences), the problem says "return it modulo 10^9 + 7". There are three reasons for that number. It is prime, which makes division possible (see below). It fits in a signed 32-bit integer. And the product of two values below it is under 2^63, so (a * b) % m fits in a 64-bit integer before the reduction.

The rules are simple. Addition, subtraction and multiplication all survive reduction: reduce after every operation and the final answer is the same as reducing once at the end.

  • (a + b) % m and (a * b) % m: reduce after each step inside the loop, not just at the end. In Python the result would still be right without it, but the numbers grow to thousands of digits and the solution times out.
  • (a - b) % m: in Python this is already non-negative. In other languages, add m before the final %.
  • Division does not survive. (a / b) % m is not (a % m) / (b % m). Instead you multiply by the modular inverse of b. When m is prime, Fermat's little theorem says b^(m-2) is that inverse, and Python computes it with three-argument pow: pow(b, m - 2, m). Python 3.8+ also accepts pow(b, -1, m).

You will rarely need the inverse in an interview. Where it appears is computing nCr mod p from factorials, which is the standard way to count combinations for large n.

Python
import math MOD = 10**9 + 7 def count_ways(n): """Climbing Stairs with 1 or 2 steps, answer mod 1e9+7.""" a, b = 1, 1 for _ in range(n): a, b = b, (a + b) % MOD # reduce after every add return a def comb_mod(n, k): """nCr mod a prime: n! / (k! (n-k)!), dividing by multiplying by inverses.""" fact = [1] * (n + 1) for i in range(1, n + 1): fact[i] = fact[i - 1] * i % MOD inv = lambda x: pow(x, MOD - 2, MOD) # Fermat: needs MOD prime return fact[n] * inv(fact[k]) % MOD * inv(fact[n - k]) % MOD assert count_ways(5) == 8assert (3 - 5) % MOD == MOD - 2 # Python % keeps it non-negativeinv3 = pow(3, MOD - 2, MOD)assert 3 * inv3 % MOD == 1assert pow(3, -1, MOD) == inv3 # Python 3.8+: built-in inverseassert comb_mod(1000, 500) == math.comb(1000, 500) % MOD # The wrong way: divide the reduced numbers as if they were the real onesfact_n = math.factorial(1000) % MODwrong = fact_n // (math.factorial(500) % MOD) ** 2print("right:", comb_mod(1000, 500), " wrong:", wrong % MOD)print("ways(1000) mod p:", count_ways(1000))
Output
Press Run (⌘ Enter) to see what happens.

The JavaScript catch: products past 2^53

JavaScript numbers are 64-bit floats, exact only up to Number.MAX_SAFE_INTEGER (2^53 − 1, about 9 × 10^15). Two values just under 10^9 + 7 multiply to about 10^18, so (a * b) % MOD silently rounds before the % and gives a wrong answer with no error. This bites people who solve a counting problem correctly in JavaScript and fail on large hidden tests.

JavaScript
const MOD = 1_000_000_007;const a = 999_999_999, b = 999_999_999; console.log("Number:", (a * b) % MOD); // product passed 2^53console.log("BigInt:", Number((BigInt(a) * BigInt(b)) % BigInt(MOD)));console.log("safe up to", Number.MAX_SAFE_INTEGER, "product is", a * b); // mulmod without BigInt: split b into 16-bit halves so no product passes 2^53function mulmod(x, y, m) { const hi = Math.floor(y / 65536), lo = y % 65536; return ((x * hi % m) * 65536 + x * lo) % m;}console.log("mulmod:", mulmod(a, b, MOD));
Output
Press Run (⌘ Enter) to see what happens.

BigInt is exact but slower, so the common pattern is plain numbers for additions (two values under 10^9 + 7 add to well under 2^53) and BigInt or a split multiply only for products.

Quick check
A JavaScript solution computes (dp[i] * dp[j]) % 1_000_000_007 and fails only on large tests. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.

Fast exponentiation

Computing x^n with a loop of n multiplications is O(n). For n = 10^18 (common in modular problems) that never finishes. Square-and-multiply reads n in binary. Keep squaring x to get x, x^2, x^4, x^8, ..., and multiply the ones whose bit is set in n into the result. That is O(log n) multiplications.

3^13 by square-and-multiply (13 = 1101 in binary)
1
0
1
1
n = 13x = 3result = 1

The bits of 13 from lowest to highest: 1, 0, 1, 1. So 13 = 1 + 4 + 8, and 3^13 = 3^1 × 3^4 × 3^8.

1/5

Pow(x, n) on LeetCode adds a twist: n can be negative. Use x^-n = (1/x)^n. In Java or C++, negating n = -2^31 overflows a 32-bit int, so you copy n into a 64-bit variable first. Python does not have that problem, but mention it: it is a classic follow-up.

Python
def my_pow(x, n): """Pow(x, n): square-and-multiply, O(log n) multiplications.""" if n < 0: x, n = 1 / x, -n # x^-n == (1/x)^n result = 1.0 while n: if n & 1: # this bit of n is set: fold the square in result *= x x *= x # x, x^2, x^4, x^8, ... n >>= 1 return result def pow_mod(base, exp, mod): result, base = 1, base % mod while exp: if exp & 1: result = result * base % mod base = base * base % mod exp >>= 1 return result assert my_pow(2.0, 10) == 1024.0assert abs(my_pow(2.0, -2) - 0.25) < 1e-12assert abs(my_pow(2.1, 3) - 9.261) < 1e-9assert my_pow(1.0, -2**31) == 1.0 # the overflow edge case in Java/C++assert my_pow(5.0, 0) == 1.0assert pow_mod(3, 200, 13) == pow(3, 200, 13)assert pow_mod(2, 10**18, 10**9 + 7) == pow(2, 10**18, 10**9 + 7)print(my_pow(2.0, 10), my_pow(2.0, -2), pow_mod(2, 10**18, 10**9 + 7))
Output
Press Run (⌘ Enter) to see what happens.

The same idea powers matrix exponentiation (Fibonacci in O(log n)), which is worth knowing exists but rarely asked.

Primes: trial division and the sieve

To test one number, try divisors up to √n. If n = a × b with both above √n, the product would exceed n, so any factor pair has one side at or below the square root. Use math.isqrt(n) rather than int(n ** 0.5), which can be off by one for large n because of float rounding.

To find all primes below n (Count Primes), use the Sieve of Eratosthenes. Start with everything marked prime. For each prime p, cross off its multiples. Two details make it fast: start crossing at p * p (smaller multiples like 2p and 3p were already crossed off by 2 and 3), and stop the outer loop once p * p >= n. The total work is O(n log log n), which is effectively linear.

Sieve of Eratosthenes up to 20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Every number from 2 to 20 starts as a candidate prime.

1/5
Python
import math def is_prime(n): if n < 2: return False for d in range(2, math.isqrt(n) + 1): # a factor pair always has one side <= sqrt(n) if n % d == 0: return False return True def count_primes(n): """Count Primes: how many primes are strictly less than n.""" if n < 3: return 0 is_p = [True] * n is_p[0] = is_p[1] = False for p in range(2, math.isqrt(n - 1) + 1): if is_p[p]: # start at p*p: smaller multiples were crossed off by smaller primes is_p[p * p :: p] = [False] * len(range(p * p, n, p)) return sum(is_p) assert [x for x in range(30) if is_prime(x)] == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]assert count_primes(10) == 4assert count_primes(0) == count_primes(1) == count_primes(2) == 0assert count_primes(3) == 1for n in range(0, 300): assert count_primes(n) == sum(is_prime(x) for x in range(n))print(count_primes(100), count_primes(1_000_000))
Output
Press Run (⌘ Enter) to see what happens.

The slice assignment crosses off a whole stride in one C-level operation, which is several times faster than a Python inner loop. That is a fair thing to say out loud if the interviewer asks about constant factors.

Counting without enumerating

Many "how many ways" problems have a closed form. Seeing it is the difference between an O(m·n) DP and one line.

Combinations. C(n, k) counts ways to choose k of n items when order does not matter. Python has math.comb(n, k) and math.perm(n, k) (ordered picks). Pascal's triangle gives the recurrence C(n, k) = C(n-1, k-1) + C(n-1, k): either the last item is in the chosen set or it is not. That recurrence is also how you build a table of combinations mod p without inverses.

Unique Paths (a robot moves only right or down across an m × n grid). Every path is exactly m - 1 downs and n - 1 rights in some order, so the count is the number of ways to choose which of the m + n - 2 moves are downs: C(m + n - 2, m - 1). Show the DP first if you like, then say "this is also a binomial coefficient", and you have shown both skills.

Permutations with repeats. The distinct arrangements of BALLOON are 7! / (2! × 2!), because swapping the two Ls or the two Os produces the same word.

Pigeonhole. If n + 1 items go into n boxes, some box holds two. It is a proof tool more than an algorithm: Find the Duplicate Number guarantees a duplicate exists because n + 1 values fall in the range 1..n. It also gives quick lower bounds, such as "among 367 people, two share a birthday".

Inclusion-exclusion. To count items in A or B, add both and subtract the overlap: |A ∪ B| = |A| + |B| − |A ∩ B|. The usual trap is the overlap. Numbers divisible by both 4 and 6 are the multiples of lcm(4, 6) = 12, not of 24.

Python
import mathfrom collections import Counter def unique_paths_dp(m, n): row = [1] * n for _ in range(1, m): for j in range(1, n): row[j] += row[j - 1] return row[-1] def unique_paths(m, n): # Every path is (m-1) downs and (n-1) rights in some order. # Choose which of the m+n-2 moves are downs. return math.comb(m + n - 2, m - 1) def pascal(rows): tri = [[1]] for _ in range(rows - 1): prev = tri[-1] tri.append([1] + [prev[i] + prev[i + 1] for i in range(len(prev) - 1)] + [1]) return tri def distinct_arrangements(word): # n! / (count_a! * count_b! * ...): swapping identical letters changes nothing total = math.factorial(len(word)) for c in Counter(word).values(): total //= math.factorial(c) return total def count_multiples(n, a, b): # Inclusion-exclusion: |A or B| = |A| + |B| - |A and B| both = a * b // math.gcd(a, b) return n // a + n // b - n // both assert unique_paths(3, 7) == unique_paths_dp(3, 7) == 28assert all(unique_paths(m, n) == unique_paths_dp(m, n) for m in range(1, 9) for n in range(1, 9))assert pascal(5)[4] == [1, 4, 6, 4, 1] == [math.comb(4, k) for k in range(5)]assert distinct_arrangements("BALLOON") == 1260assert math.perm(5, 2) == 20 # ordered picks: 5 * 4assert count_multiples(100, 3, 5) == sum(1 for x in range(1, 101) if x % 3 == 0 or x % 5 == 0) == 47assert count_multiples(100, 4, 6) == 33 # lcm is 12, not 24print(unique_paths(3, 7), distinct_arrangements("BALLOON"), count_multiples(100, 3, 5))
Output
Press Run (⌘ Enter) to see what happens.

Number limits by language

Interviewers ask overflow questions because production bugs come from them. Know the limits of the language you code in.

  • Python integers are arbitrary precision. 2**100 is exact. Overflow never happens, but huge numbers get slow, which is why you still reduce mod p.
  • JavaScript numbers are exact integers only up to 2^53 − 1. Past that, 2**53 + 1 === 2**53. Use BigInt (10n) for exact large values; note that BigInt division truncates toward zero like the rest of JavaScript, and you cannot mix BigInt and Number in one expression.
  • Java, C++, Go have fixed-width ints. A 32-bit int holds about ±2.1 × 10^9.

Reverse Integer exists to test this: reverse the digits and return 0 if the result leaves the signed 32-bit range. In Python you check the range at the end. In a fixed-width language you must check before the multiply that would overflow, with rev > (INT_MAX - digit) / 10.

Python
def reverse_32(x): """Reverse Integer: return 0 if the result leaves the signed 32-bit range.""" sign = -1 if x < 0 else 1 r = sign * int(str(abs(x))[::-1]) return r if -2**31 <= r <= 2**31 - 1 else 0 assert reverse_32(123) == 321assert reverse_32(-120) == -21assert reverse_32(1534236469) == 0 # 9646324351 does not fitprint(2**100, reverse_32(1534236469))
Output
Press Run (⌘ Enter) to see what happens.
JavaScript
console.log(Number.MAX_SAFE_INTEGER); // 2^53 - 1console.log(2 ** 53 === 2 ** 53 + 1); // true: the +1 is lostconsole.log(9007199254740993); // prints ...992console.log(2n ** 64n); // BigInt is exactconsole.log(10n / 3n, -7n / 2n, -7n % 3n); // BigInt division truncates
Output
Press Run (⌘ Enter) to see what happens.

Fair randomness

Randomness questions test whether every outcome is equally likely, and the wrong answers usually look fine on a quick test.

Fisher-Yates shuffle. Walk from the end. At position i, swap with a random index from 0 to i inclusive. Each of the n! orders has probability exactly 1/n!. The common wrong version swaps each position with a random index from the whole array. That produces n^n equally likely swap sequences, and n^n is not divisible by n! (27 is not divisible by 6), so some orders must come up more often. The run below shows the bias.

Reservoir sampling (Linked List Random Node). You see a stream of unknown length and must return one item uniformly at random using O(1) memory. Keep the k-th item with probability 1/k. The first item survives to the end with probability 1 × 1/2 × 2/3 × ... × (n-1)/n = 1/n, and the same telescoping works for every item.

Random Pick with Weight. Build prefix sums of the weights, draw a number in [0, total), and binary search for the first prefix greater than it. Index i owns a slice of width w[i]. This is bisect_right from Binary Search with the prefix array from Prefix Sums and Difference Arrays.

Python
import randomfrom bisect import bisect_rightfrom collections import Counterfrom itertools import accumulate def shuffle(a): """Fisher-Yates: every one of the n! orders is equally likely.""" for i in range(len(a) - 1, 0, -1): j = random.randint(0, i) # inclusive of i: an item may stay put a[i], a[j] = a[j], a[i] return a def reservoir_pick(stream): """Pick one item uniformly from a stream of unknown length, O(1) memory.""" chosen = None for count, item in enumerate(stream, start=1): if random.randrange(count) == 0: # keep the new item with probability 1/count chosen = item return chosen class WeightedPicker: """Random Pick with Weight: prefix sums + binary search.""" def __init__(self, weights): self.prefix = list(accumulate(weights)) # [1, 3, 6] for [1, 2, 3] def pick(self): target = random.randrange(self.prefix[-1]) # 0 .. total-1 return bisect_right(self.prefix, target) random.seed(7)TRIALS = 60_000 orders = Counter(tuple(shuffle([1, 2, 3])) for _ in range(TRIALS))assert len(orders) == 6assert all(abs(c / TRIALS - 1 / 6) < 0.01 for c in orders.values()) picks = Counter(reservoir_pick(iter("abcd")) for _ in range(TRIALS))assert all(abs(c / TRIALS - 0.25) < 0.01 for c in picks.values()) wp = WeightedPicker([1, 2, 3])got = Counter(wp.pick() for _ in range(TRIALS))for idx, w in enumerate([1, 2, 3]): assert abs(got[idx] / TRIALS - w / 6) < 0.01 def naive_shuffle(a): for i in range(len(a)): j = random.randint(0, len(a) - 1) # BUG: picks from the whole array a[i], a[j] = a[j], a[i] return a bad = Counter(tuple(naive_shuffle([1, 2, 3])) for _ in range(TRIALS))print("fisher-yates:", sorted(round(c / TRIALS, 3) for c in orders.values()))print("naive: ", sorted(round(c / TRIALS, 3) for c in bad.values()))
Output
Press Run (⌘ Enter) to see what happens.

At work, use the library (random.shuffle, random.choices(population, weights=...)), and use the secrets module rather than random for anything an attacker could benefit from predicting, such as tokens or a prize draw.

Quick check
In reservoir sampling, you are on the 5th item of the stream. With what probability do you replace the current choice with it?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Match each problem to the math that solves it.

Choose an item, then its match on the other side.
Quick check
Why do problems so often ask for the answer modulo 10^9 + 7?
Need a nudge? A hint rules out a wrong answer.

How it shows up in interviews

Math questions are usually short, and the grading is about precision: do you know the edge cases without being told? Say the range of n, say whether the language can overflow, say which way division rounds, and test zero, one and negative inputs. If a "how many ways" DP has a binomial shape, offer the closed form after the DP. If randomness is involved, argue why each outcome has the same probability rather than saying "it looks random".

Key terms
GCD
The largest number dividing both inputs. Euclid computes it with gcd(a, b) = gcd(b, a % b) in O(log n).
modular inverse
The value b' with b * b' % m == 1. For prime m it is pow(b, m - 2, m), and it replaces division under a modulus.
square-and-multiply
Fast exponentiation that squares the base and multiplies in the powers whose bit is set in n. O(log n) multiplications.
Sieve of Eratosthenes
Finds every prime below n by crossing off multiples of each prime from p × p upward. O(n log log n).
binomial coefficient
C(n, k), the number of ways to choose k items from n when order does not matter. math.comb in Python.
Fisher-Yates shuffle
Swap each position i, from the end, with a random index in 0..i. Every order is equally likely.
reservoir sampling
Choosing uniformly from a stream of unknown length by keeping the k-th item with probability 1/k.