Skip to content
Tech Interview Prep
Technical interview guide

Math & Geometry

Problems that lean on a specific mathematical insight (number theory, combinatorics, or coordinate geometry) rather than a general algorithmic pattern.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with integer semantics cited from CPython 3.14.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-8

Teach the sieve of Eratosthenes to an engineer who has only seen it as a rule of thumb.

Answer

The 90-second answer

The sieve answers "which numbers up to n are prime" in one pass, without ever testing a number for primality. Keep a boolean array is_prime[0..n], all true. Walk p from 2 upward; when is_prime[p] is still true, p is prime, so mark every multiple of p from p² onward as composite. Stop when p² > n. Everything still true is prime.

Two things make it work. First, the invariant: when you reach p, every composite ≤ p² has already been marked by a smaller prime factor, so an unmarked p is genuinely prime. Second, starting at p² rather than 2p: the multiples 2p, 3p, …, (p−1)p were already marked by 2, 3, …, p−1. That is not an optimisation you can skip: it is what makes the total work O(n log log n) instead of O(n log n).

Bound semantics matter: this returns primes ≤ n inclusive, array length n+1. "Primes below n" is a different contract.

Code

Python
def sieve(n):
    """is_prime[i] == 1 iff i is prime, for 0 <= i <= n."""
    is_prime = bytearray([1]) * (n + 1)
    if n >= 0: is_prime[0] = 0
    if n >= 1: is_prime[1] = 0
    p = 2
    while p * p <= n:
        if is_prime[p]:
            is_prime[p*p::p] = bytearray(len(range(p*p, n + 1, p)))
        p += 1
    return is_prime

Trace, n = 30

  • p=2: prime. Mark 4, 6, …, 30.
  • p=3: prime. Mark 9, 12, …, 30.
  • p=4: is_prime[4] == 0, skip.
  • p=5: prime. Mark 25, 30.
  • p=6: 36 > 30, stop.

Survivors: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.

Why log log n

Total marking writes = Σ n/p over primes p ≤ √n. For n = 10⁶ that is ≈ 2.9×10⁶ writes (n·ln ln n ≈ 2.63×10⁶ plus the constant term). Trial division of all 10⁶ values by the 168 primes ≤ 1000 is up to 1.7×10⁸ modulo operations. Same answer, roughly 60× fewer operations, and each is a store rather than a division.

Failure modes

  • Memory: the bytearray is 1 byte per number. 1 GB at n = 10⁹. Bit-packed it is 125 MB. The slice assignment also allocates a temporary: at n = 10⁹, marking p=2 allocates a 500 MB temp. Chunk the marking or use a segmented sieve.
  • n = 0 or 1: the guards exist because is_prime[0] would otherwise be 1.
  • Sparse queries: if you need primality for 20 numbers near 10¹², sieving to 10¹² is absurd. Miller–Rabin, or trial division by primes ≤ 10⁶, wins.

When not to use it

Sieve when queries are dense within a known bound. Test individually when they are sparse or the values sit far above any bound you would want to allocate.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2

Walk through negative values under modulo, including where engineers most often get it wrong.

Answer

Two conventions, and which one you get is decided by how the language rounds integer division.

The identity is a = n * q + r. The language picks q, and r falls out of it. Round q toward zero (truncation) and r carries the sign of a. Round q toward negative infinity (floor) and r carries the sign of n.

Language-7 % 3q = -7 / 3Rounding
C (C99+), C++ (C++11+), Java, Go, JS, Rust %, MySQL, Postgres-1-2truncate toward zero
Python, Ruby, Haskell mod2-3floor
Java Math.floorMod(-7, 3)2—floor
Rust (-7i32).rem_euclid(3)2—floor

Both rows satisfy the identity: 3 * -2 + (-1) = -7 and 3 * -3 + 2 = -7. Both are correct remainders; they are different q.

Before C99, % with a negative operand was implementation-defined in C; C99 and C++11 pinned it to truncation. Java's JLS 15.17.3 says the remainder "has the same sign as the dividend"; Python's docs say the result "has the same sign as the divisor".

The portable normalisation is ((a % n) + n) % n for n > 0. The second % n is not decoration. In a truncating language r ∈ (-n, n), so r + n ∈ (0, 2n): for a positive dividend, r + n can already be ≥ n. 7 % 3 + 3 = 4, which is not a valid index. Adding n once only repairs the negative half.

Where it bites:

  • Ring buffer: (write - read) % cap goes negative the moment write wraps past read.
  • Hash bucket: hash % m with a signed hash yields a negative bucket. In C that is out-of-bounds; in Java it is ArrayIndexOutOfBoundsException.
  • Date arithmetic: day-of-week from a negative day offset.

The dangerous case is Python, where arr[-1] is legal and reads the last element. A negative index there does not crash: it silently returns the wrong element, and the bug survives every test whose inputs happen not to go negative. In C, Java or Go the same bug is loud. That asymmetry is why the mistake ships out of Python prototypes.

Two fixes that look right and are not: abs(a % n) gives 1 for -7 % 3 in C, not 2; and (a % n) + n without the final reduction breaks positive dividends as shown above.

Floats are a separate trap. Python's % floors on floats too, -7.0 % 3.0 == 2.0, while math.fmod(-7.0, 3.0) == -1.0, matching C's fmod. Same language, two answers, depending on which function you call.

Detection: property-test the index expression with negative operands and assert 0 <= idx < n.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

What would you ask a candidate who recites digit manipulation but cannot apply it?

Answer

The follow-up I'd ask: "Run your function on n = 0, then on n = -123. Tell me what it prints."

Not "explain your approach": that lets them re-recite. Handing over two inputs and asking for the output forces execution, and both inputs break the standard loop.

Then, in order:

  1. n = 0. The loop while n: never runs, so the function returns [] for a number that has one digit. A candidate who recites the loop but never ran it misses this every time.

  2. n = -123. This is the one that separates people. In Python, -123 % 10 == 7 and -123 // 10 == -13 (floor division), so the digits come out 7, 7, 8, 9, and then -1 // 10 == -1, so the loop never terminates. It hangs. In C or Java, / truncates toward zero: -123 / 10 == -12, -123 % 10 == -3, so you get negative digits -3, -2, -1. Same recitation, two different wrong answers depending on the language's division semantics. Ask which one they're in and why.

  3. Change the base. "Same function, base 16." The mechanism is identical (% 16, // 16), so a candidate with a mental model transfers it in seconds; a candidate with a memorised snippet stalls.

  4. Change the constraint. "Now do it without arithmetic: only string operations." This tests whether they know the alternative and its costs, not just that it exists.

The trade-off, which is where the "apply" part lives:

modulo loopstr(n)
exact for big intsyesyes, but Python 3.11+ caps int↔str at 4300 digits by default (sys.set_int_max_str_digits)
allocationO(1) extra per stepone string of length d
baseany base, one constantbase 10 only (or format/bin/hex)
negativeslanguage-dependent, must handlesign handled by the formatter
localenoneformat with an n spec can add grouping

Deciding criterion: if the digits feed arithmetic or a hash, use the loop; if they feed display, use the formatter and let it own sign and grouping. The loop is O(d) time, O(d) output, d = number of digits ≈ log10(n).

Failure modes to name: the zero case (empty output), the negative case (infinite loop in Python, negative digits in C/Java), and Math.abs(Integer.MIN_VALUE) in Java returning a negative number, so the digit loop on -2147483648 is wrong even after the abs "fix".

What I'm listening for: they run the code in their head, they name the language's division rule, and they say which inputs they'd test. Reciting the loop is table stakes; predicting its output on 0 and -123 is the job.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

A teammate proposes a design that hinges on the greatest common divisor. How do you evaluate it?

Answer

Start with what the design needs the GCD for. "Hinges on the GCD" usually means one of three things: reducing a ratio to lowest terms, aligning two periods (lcm), or checking coprimality before computing a modular inverse. Each has a different correctness bar, so the first move is to name which one, then state the input domain: machine ints or bignums, bounded or not, hot path or offline. The evaluation is four questions: does the design need a gcd at all, is the primitive right, does it hold across the input domain, and what does it cost on the real distribution.

Is the primitive right? Euclid is the default: each step replaces (a, b) with (b, a mod b). The remainder at least halves every two steps, so it terminates in O(log min(a,b)) mod operations. Trace it:

gcd(1071, 462): 1071 = 2·462 + 147 → (462, 147); 462 = 3·147 + 21 → (147, 21); 147 = 7·21 + 0 → 21. Three steps.

The worst case is consecutive Fibonacci numbers, where every quotient is 1: gcd(89, 55) takes nine steps, and gcd(F_{n+1}, F_n) takes n−1. That matters here, because a uniform random input distribution never gets near it: a design that looks fast in a smoke test can be several times slower on adversarial inputs.

What is it using instead? If it factorises both numbers and intersects the prime multisets, that is correct but sub-exponential (GNFS), not exponential: still the wrong tool when Euclid is O(log min(a,b)) steps. If the design needs Bézout coefficients or a modular inverse, plain gcd is insufficient and extended Euclid is the primitive.

NeedPrimitiveCost
exact gcdEuclidO(log min(a,b)) mod ops
gcd where division is slowbinary GCD (shifts, subtracts)same bit complexity, cheaper constant
Bézout coefficients / modular inverseextended Euclidsame as Euclid
lcma // gcd(a,b) * bone gcd plus one multiply

Failure modes to look for. Overflow: a * b // gcd(a,b) wraps in fixed-width ints and returns a silently wrong lcm; divide first. Sign and zero: gcd(0,0) = 0 and gcd(a,0) = |a|, and C's % can return a negative remainder, so a hand-rolled loop needs abs. Wrong primitive: using gcd to test primality, or to compare floats, is a category error, not a tuning problem.

What to measure. If the call sits on a per-request path, benchmark with Fibonacci-adjacent inputs rather than random ones, and confirm the input range actually reaches bignum territory where the bit-complexity term dominates the constant.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does modular inverse guarantee, and what does it deliberately leave open?

Answer

Core answer. A modular inverse of a mod m is the residue class b with a·b ≡ 1 (mod m). It guarantees exactly two things: that class exists, and that it is unique mod m, and only when gcd(a, m) = 1. What it leaves open is everything else: which integer you write down for b (b, b + m, b - m are the same inverse), how you compute it, what that costs, and whether m is prime. Coprimality is the whole precondition; primality is a convenience, not a requirement.

Why coprimality is the precondition. If d = gcd(a, m) > 1, then a·b is always a multiple of d, so a·b mod m is a multiple of d and can never be 1. Take a = 6, m = 9: 6b mod 9 ∈ {0, 3, 6} for every b. No inverse. When gcd = 1, Bézout gives x, y with a·x + m·y = 1, so a·x ≡ 1 (mod m) and x is the inverse. Uniqueness follows because two inverses b, b' give a(b - b') ≡ 0, and a invertible forces b ≡ b'.

Computing it: three options, different assumptions.

MethodRequiresCostNotes
Fermat: pow(a, m-2, m)m primeO(log m) mults (~30 for 1e9+7)cheapest when primality is guaranteed
Extended Euclidgcd(a,m)=1O(log m) stepsworks for any modulus
Precompute inv[1..n]m prime, n < mO(n) once, O(1) lookupinv[i] = -(m//i)*inv[m%i] % m

Python 3.8+ exposes pow(a, -1, m), which uses extended Euclid and raises ValueError when gcd(a,m) != 1: that exception is your detection mechanism.

Trace. m = 7, a = 4. Euclid: 7 = 1·4 + 3, 4 = 1·3 + 1, 3 = 3·1 + 0. Back-substitute: 1 = 4 - 3 = 4 - (7 - 4) = 2·4 - 7, so inv = 2. Check 4·2 = 8 ≡ 1 (mod 7). Fermat agrees: 4^5 mod 7 = 2.

Failure mode. Fermat on a composite modulus returns a wrong number silently. m = 9, a = 4: gcd = 1, true inverse is 7 (4·7 = 28 ≡ 1). pow(4, 7, 9) = 4, not 7: no error, just a wrong answer. The other classic: (6 // 4) % 7 = 1, but 6 · inv(4) mod 7 = 6·2 mod 7 = 5, and 4·5 = 20 ≡ 6 (mod 7). Integer division does not commute with reduction.

Choosing. If the modulus is a fixed prime (1e9+7, 998244353), Fermat or a precomputed table. If the modulus is arbitrary or you cannot prove primality, extended Euclid, pow(a, -1, m), and let the ValueError enforce coprimality. Precompute when you need many inverses over a small range; the O(n) table beats O(n log m) individual calls.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Describe fast exponentiation and the evidence you would collect before relying on it.

Answer

Fast exponentiation computes b^e in O(log e) multiplications instead of O(e). The loop maintains one invariant: r · b^e ≡ b^E (mod m), where E is the original exponent. Each iteration looks at the low bit of e. If it is set, the current b is folded into r; then b is squared and e is shifted right one bit. Squaring advances b from b^(2^k) to b^(2^(k+1)); the shift discards the bit just consumed. When e reaches 0, r equals b^E.

Python
def power(b, e, m):
    r = 1
    while e:
        if e & 1:
            r = r * b % m
        b = b * b % m
        e >>= 1
    return r

Trace with b=2, e=1_000_000, m=10**9+7. The exponent is 0xF4240: 20 bits, popcount 7. The loop runs 20 iterations, doing 20 squarings and 7 multiplies: 27 modular multiplications. The naive loop does 999,999. Python's built-in pow(2, 1_000_000, 10**9+7) runs the same algorithm in C.

Evidence to collect before relying on it:

  • Differential correctness. Compare against pow(b, e, m) and against a naive loop for small e, over random b, e, m. Add the property pow(b, e1+e2, m) == pow(b, e1, m) * pow(b, e2, m) % m.
  • Edge cases. e=0, m=1, b=0, b≥m, negative e. These are where the loop breaks (below).
  • Performance. Benchmark against the built-in. In CPython the hand-rolled loop is typically 50-100x slower, because every iteration is interpreted rather than run in C.

Alternatives. In Python, pow(b, e, m) is the default: same algorithm, C speed, correct edge cases. Hand-roll only in a language without it, or for a different semiring. Matrix exponentiation computes M^e in O(n^3 log e) and is the tool for linear recurrences such as Fibonacci, where the base is a matrix and multiplication is not commutative.

Failure modes:

  • Overflow. In C or Java, b * b overflows a 64-bit int before the mod. Use a 128-bit intermediate or Montgomery multiplication. Python's arbitrary-precision ints do not overflow.
  • Non-commutative bases. For matrices, r = r * b and r = b * r differ. Keep the order consistent with how the exponent was decomposed.
  • e=0 with m=1. The loop returns r=1; the correct value is 1 % m = 0. pow(2, 0, 1) is 0.
  • Negative e. In Python, -1 >> 1 stays -1, so the loop never terminates. Negative exponents need a modular inverse (b^(m-2) mod m for prime m), which requires gcd(b, m) = 1.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Where does primality testing matter, and where is it irrelevant?

Answer

Primality testing earns its keep in exactly two situations: you have to generate a prime, or you have to verify one that someone else may have chosen adversarially. RSA and Diffie-Hellman key generation are the canonical case: sample random odd numbers of the target bit length and test until one passes. It is irrelevant when the hard problem is factoring (primality is the easy half of the RSA story), when you want all primes up to N (a sieve beats testing each one), and when a composite modulus does the job: power-of-two hash table sizes with a decent finalizer, for instance.

Why generation is the case that matters

For a 2048-bit RSA prime, the density of primes near 2^2048 is about 1/ln(2^2048) ≈ 1/1420. You only sample odd candidates, so you expect to test roughly 710 numbers before one is prime. That is why the per-candidate test has to be cheap: you cannot sieve a 2048-bit range, and trial division to √n is hopeless (√n ≈ 2^1024). The standard pipeline is trial division by small primes as a filter, then Miller-Rabin.

Trial division by every prime below 2000 rejects all but about ∏(1−1/p) ≈ 7% of candidates: roughly 93% die for the cost of a few dozen divisions. Miller-Rabin runs on the survivors. Each round is one modular exponentiation, O(log³ n) with schoolbook multiplication. The error bound is 4^−k over k random bases, but that bound is worst-case over adversarial inputs, so practice uses far fewer rounds than the bound suggests: FIPS 186-4 tabulates the count by bit length rather than mandating a blanket 64.

Where it is irrelevant, and why

  • Factoring. RSA's security rests on factoring n = pq being hard. AKS (2002) tests primality in polynomial time and changes nothing about factoring. If your problem is "what are the factors", primality testing is the wrong tool.
  • Enumerating primes. For all primes below 10^7, a sieve of Eratosthenes is O(N log log N), about 3×10^7 operations, versus 10^7 separate tests. Sieve when you want the set, test when you want one answer.
  • Hash tables. Java's HashMap, Go's map and Python's dict all use power-of-two capacities with a mixing function. Prime table sizes are a workaround for weak modulo hashing; with a good finalizer, masking is faster than division and primes buy nothing.
  • Named constants. Curve field primes, Mersenne primes for PRNG periods: you hardcode them. No test runs at runtime.

Failure modes worth naming

  • Fixed bases against adversarial input. 3215031751 = 151 × 751 × 28351 is a strong pseudoprime to bases 2, 3, 5 and 7. A "deterministic" test with those bases accepts it. Use random bases, or the 12-prime set {2,…,37}, which is proven deterministic for n < 3.3×10^24.
  • Fermat instead of Miller-Rabin. Carmichael numbers (561 = 3×11×17, 1105, 1729) pass Fermat for every coprime base. Miller-Rabin's 4^−k bound is what you want.
  • Weak primes. A prime p where p−1 is smooth falls to Pollard's p−1. Libraries check for a large prime factor in p−1; hand-rolled generators often do not.

The test itself

Python
import random

def is_probable_prime(n, rounds=40):
    if n < 2:
        return False
    for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
        if n % p == 0:
            return n == p          # small prime, or a small factor
    d, s = n - 1, 0
    while d % 2 == 0:              # n - 1 = 2^s * d with d odd
        d //= 2
        s += 1
    for _ in range(rounds):
        a = random.randrange(2, n - 1)
        x = pow(a, d, n)
        if x == 1 or x == n - 1:
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False           # a is a witness that n is composite
    return True

Trace on n = 41: the pre-filter finds no divisor ≤ 37. n−1 = 40 = 2³·5, so d = 5, s = 3. Base a = 2: x = 2⁵ mod 41 = 32, which is neither 1 nor 40. Square it: 32² = 1024 = 41·24 + 40, so x = 40 = n−1 → break, round passes. On n = 1373653 = 829 × 1657 (a strong pseudoprime to bases 2 and 3), base 2 passes but a random base rejects it with probability ≥ 3/4, so 40 rounds make acceptance of a composite negligible.

MethodCostDeterministicUse when
Trial division to √nO(√n)yesn below ~10^12, or as a pre-filter
Sieve of EratosthenesO(N log log N)yesall primes up to N
Miller-Rabin, k random basesO(k log³ n)no, error ≤ 4^−kkey generation
Miller-Rabin, bases 2…37O(log³ n)yes for n < 3.3×10^2464-bit inputs
Baillie-PSWO(log³ n)no known counterexamplewhen you want no known pseudoprime
AKSO(log⁶ n)yestheory; constants too large in practice

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

What is the smallest experiment that would change your mind about the pigeonhole principle?

Answer

Core answer, say this first. No experiment can change your mind about the pigeonhole principle. It is a theorem, not a hypothesis: if f maps a finite set D of size n into a set C of size m with n > m, then f is not injective. The proof is three lines, if f were injective then |f(D)| = n, but f(D) ⊆ C so |f(D)| ≤ m < n, a contradiction. No observation refutes that. What an experiment can change is your belief that the principle applies to the system in front of you. So the smallest experiment is the cheapest check of its two premises: the domain is finite with a known size n, the map is a total function into a codomain of known size m, and n > m. Break any one and the principle is silent.

The experiment. Take a real claim: "100k rows hashed into a 16-bit column must collide." Pigeonhole agrees. 100,000 > 65,536. The falsifiable part is "16-bit column." One query settles it:

Python
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE t (h INTEGER)")      # SQLite INTEGER is 64-bit signed
con.execute("INSERT INTO t VALUES (?)", (65535,))
con.execute("INSERT INTO t VALUES (?)", (65536,))
print(con.execute("SELECT COUNT(DISTINCT h) FROM t").fetchone()[0])

Output: 2. The column holds 64 bits, so m = 2^64, not 2^16, and 100k rows no longer guarantee a collision. The theorem was never in doubt; the bucket count was wrong. That is the whole shape of the experiment: you test the model, not the theorem.

When the principle is the wrong tool. It gives existence, never the witness. If you need the colliding pair, pigeonhole is useless on its own: sort and scan (O(n log n)), hash with chaining (O(n) expected), or Floyd/Brent cycle detection (O(1) space) for the bounded-state case. And if you need a probability rather than a guarantee, you want the birthday bound, which is a different claim. For m = 2^32 buckets, the chance of a collision crosses 50% at about 1.177·sqrt(2^32) ≈ 77,000 items; a guarantee needs 2^32 + 1. Confusing the two is the most common error: "we'll collide eventually" is not "we'll collide at 77k."

Failure modes. (1) Bucket count taken from a comment rather than the type, as above; detect by asserting the storage width. (2) Treating a projection as the state: a cycle detector watching a 32-bit counter when the real state is 64-bit reports a cycle that does not exist in the real system; detect by comparing observed cycle length against the claimed state-space size. (3) Unbounded domain: a stream with no fixed bound has no n, so the principle says nothing. Detect by checking that the domain size is a constant in the code, not a runtime counter.

The defensible position. The principle is a tautology over finite sets; the only thing an experiment can falsify is your encoding of the problem as one. So the smallest experiment is always the same: verify n, verify m, verify the map is total. One query, one assertion, one type check.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

What trade-off does combinatorial counting force that a junior answer usually skips?

Answer

The trade-off is exactness versus tractability, and it is forced by the gap between how fast the count grows and how cheap the formula is.

A closed-form count: n!, C(n,k), the multinomial: costs a handful of arithmetic operations no matter how large n gets. Enumeration costs one step per configuration, and the number of configurations grows exponentially. So the formula is not merely faster; it is the only thing that stays computable. The price is that the formula is a bet on structure: that the items are uniform, that the choices are independent, and that "distinct" has a fixed meaning. The junior answer recites the formula and never names the bet.

Mechanism. C(n,k) = n!/(k!(n-k)!) collapses k! orderings into one, which is correct only if those orderings are genuinely indistinguishable. n^k assumes each of k positions draws independently from n options. Break either assumption and the closed form returns a number that is exact for a different problem.

Worked example. A fleet of 8 nodes, each in one of 3 states, independent: 3^8 = 6,561 configurations. You can enumerate that in a test. Scale to 30 nodes: 3^30 ≈ 2.06 × 10^14. Same formula, same O(1) cost, but enumeration is now off the table. If the nodes share a rack power domain, the independence assumption is false and 3^30 over-counts: states where one rack is down while its nodes report "up" are counted but cannot occur.

Alternatives, and when each wins:

ApproachCostExact?Valid when
Closed formO(1)yesuniformity and independence hold
Enumerationone step per configyescount is small enough to walk (≲ 10^7 in a test)
Monte Carlofixed sample budgetnoyou need a magnitude, not a proof

To pin a proportion near 0.5 to ±1% you need about 10,000 samples (SE = 0.5/√N, so N = 10,000 gives SE = 0.005).

Failure modes. Applying an ordered count where order is irrelevant over-counts by exactly k!: choosing 3 of 10 gives 720 ordered versus 120 unordered, a factor of 6. It survives casual testing because the happy path hides it. Sampling hides a different failure: the error bar is real, and a 10,000-sample estimate can be off by more than the difference you are trying to detect.

So the trade-off the junior skips: the closed form is cheap and exact only for the idealized problem, and the moment the structure assumption fails you must pay either exponential enumeration or accept sampling error. The senior answer states which of the three it is relying on, and why the assumption holds.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

How would you brief product on why computing binomial coefficients safely delays a ship date?

Answer

The 90-second version

"The feature slips a day. The fast version is already written and passes every test we have: it slips because that version returns a wrong number, silently, once the input crosses a threshold, and we can't ship a figure we can't bound. Two ways out: ship today with the input capped, or wait a day for the version that's correct across the range. That's the call I need from you."

Assumptions I'd state before that: the code is in a fixed-width language (Java, Go, C++, Rust). In Python math.comb is exact and arbitrary-precision, so there is no overflow and no delay: the whole conversation is language-dependent.

Why it's silent

The naive implementation computes n! and k! and divides. In Java a long tops out at 9,223,372,036,854,775,807. 20! = 2,432,902,008,176,640,000 fits; 21! = 51,090,942,171,709,440,000 does not. So the factorial path wraps at n = 21, while the answer you actually want, C(60,30) = 118,264,581,564,861,424, fits in a long with room to spare. The intermediate is the problem, not the result. Wrapping doesn't throw; it returns a plausible-looking integer, which is why no test caught it.

The fix, and what it costs

Interleave the multiply and divide so every step is exact:

Java
// Java 17
static long comb(int n, int k) {
    k = Math.min(k, n - k);          // keeps the loop and the products small
    long r = 1;
    for (int i = 1; i <= k; i++) {
        r = r * (n - k + i) / i;
    }
    return r;
}

Trace C(6,3): r=1 → i=1: 1·4/1 = 4 → i=2: 4·5/2 = 10 → i=3: 10·6/3 = 20. C(6,3) = 20.

Every intermediate is ≤ the final result, so for C(60,30) the largest value held is 1.18e17 and the largest intermediate product is 3.55e18 (C(59,29)·60): both inside long. The code is half a day. The boundary tests at n = 20 and n = 21 are the rest of it, and they're the part that can't be skipped, because the bug only appears at the boundary.

If the consumer only needs the value mod a prime (a hash, a count mod 1e9+7) precompute factorials and inverse factorials in O(n). Faster, but you can no longer print or compare exact values. That's a semantics change, so it's product's call, not mine.

What product decides

OptionWorkRiskShips
Naive factorial0wrong values for n ≥ 21, no error raisedtoday
Interleaved loop~0.5 day + boundary testscorrect while the result fits int64+1 day
Modular precompute~1 dayonly if the consumer accepts mod p+1–2 days
Cap input at 20~2 hoursfeature limited to small ntoday

What would change the estimate

If the input domain is provably below 21, ship today with an assertion. If the value is only consumed mod p, the modular path is a day and no cap. If the service is Python, none of this applies.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain integer overflow in intermediate results and how it changes a production decision.

Answer

An expression whose final value fits the type can still overflow on the way there. The overflow happens in an intermediate step, so checking the result is not enough: you change the order of operations or widen the intermediate. That choice is a production decision: it sets whether a counter column is int or bigint, whether a duration is stored in milliseconds or nanoseconds, and whether a midpoint is computed as (lo + hi) / 2 or lo + (hi - lo) / 2.

Mechanism. Multiplication before division and addition before subtraction are the two shapes. a * b can exceed the type even when a * b / c fits. Accumulators have the same problem: a running sum of many small values overflows even though every term is small. The type of the expression is fixed by the operands, not by the value: C and Java both compute int * int in 32 bits regardless of what you assign it to.

Trace.

C
#include <stdint.h>
int a = 100000, b = 100000, c = 100000;
int bad  = (a * b) / c;            // signed overflow
int good = (a / c) * b;            // 100000
int64_t ok = (int64_t)a * b / c;   // 100000

a * b is 10^10 = 10000000000, above INT_MAX (2147483647). In C that is undefined behaviour; with wrapping arithmetic (gcc -fwrapv, or the hardware's two's complement) it wraps to 10000000000 − 2·2^32 = 1410065408, and 1410065408 / 100000 = 14100. So the expression that "obviously" returns 100000 returns 14100. Java defines the same wrap, so it gives 14100 deterministically. (a / c) * b is exact only because c divides a; otherwise it truncates. (int64_t)a * b / c is the general fix.

Failure modes. The wrong answer is silent: no crash, no exception, just 14100. In C/C++ signed overflow is UB, so the compiler may also fold if (x + 1 > x) to true. Detection: build with -fsanitize=signed-integer-overflow (UBSan), and in Java use Math.addExact / Math.multiplyExact, which throw instead of wrapping. Tests miss it because the happy path uses small inputs; you need boundary inputs near the type limit. Postgres behaves differently again: an int * int that overflows raises ERROR: integer out of range rather than wrapping, so the bug surfaces as a failed query, not a wrong number.

The production decision. The canonical case is binary search: int mid = (lo + hi) / 2 overflows once lo + hi > INT_MAX, i.e. arrays longer than 2^30 elements. Java's Arrays.binarySearch carried this until JDK 6 (fixed 2006); the fix is lo + (hi - lo) / 2. The same arithmetic decides storage: 2^31 milliseconds is about 24.8 days, so an int millisecond timestamp overflows within a month of epoch, while int64 nanoseconds covers ~292 years. Widening is not free (8 bytes instead of 4, and it can break index and API compatibility) so the decision is usually "widen the one field that accumulates" rather than "use bigint everywhere". Reordering is free but only valid when the division is exact; arbitrary precision is correct everywhere and pays allocation cost per operation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

What causes catastrophic cancellation in floating-point operations, and what algorithmic refactorings or algebraic reformulations prevent severe loss of precision?

Answer

Catastrophic cancellation is the loss of significant digits when you subtract two nearly equal quantities that are themselves the results of earlier rounding. The subtraction is exact: IEEE 754 requires it, and Sterbenz's lemma guarantees x - y is computed exactly whenever y/2 ≤ x ≤ 2y, but exactness is the problem. The leading bits that cancel were the only bits carrying signal; what remains is the rounding error already sitting in the low-order bits, and normalisation promotes that noise to the top of the significand.

The quantitative statement: if x and y carry relative error eps ≈ 2^-53, the computed difference has relative error bounded by

|error(x - y)| / |x - y|  ≲  eps * (|x| + |y|) / |x - y|

The amplification factor is the ratio of operand magnitude to result magnitude. When x ≈ y, that ratio explodes. Every fix is the same idea: reformulate so the subtraction never happens, or compute the small quantity directly.

Worked example

f(x) = sqrt(1 + x) - 1 near zero. Take x = 2^-52, exactly one ulp above 1.0.

Python
import math

x = 2.0**-52
naive  = math.sqrt(1.0 + x) - 1.0
stable = x / (math.sqrt(1.0 + x) + 1.0)

print(naive)   # 0.0
print(stable)  # 1.1102230246251565e-16

Trace: 1.0 + x is exact. It is the next double after 1.0. Its square root is 1 + 2^-53 - 2^-107, which sits just below the midpoint between 1.0 and 1 + 2^-52, so correctly-rounded sqrt returns 1.0. Subtracting 1.0 yields 0.0: 100% relative error. The conjugate form evaluates to 2^-52 / 2 = 2^-53 = 1.1102230246251565e-16, the correctly rounded true value (the exact value is 2^-53 - 2^-107).

Reformulations

  1. Conjugate / rationalisation. sqrt(1+x) - 1 = x / (sqrt(1+x) + 1). The subtraction becomes an addition of two positive terms.
  2. Quadratic formula. For ax² + bx + c with b² ≫ 4ac and b > 0, the root (-b + sqrt(b² - 4ac)) / (2a) cancels. Compute q = -(b + sign(b)·sqrt(b² - 4ac)) / 2, then x₁ = q/a and x₂ = c/q. The second root comes from the product of roots, c/a, instead of a subtraction.
  3. Library primitives. expm1(x) = e^x - 1 and log1p(x) = ln(1 + x) are specified to stay accurate near zero; they never form 1 + x or e^x and then subtract.
  4. Compensated summation (Kahan / Neumaier) for long sums: a running correction term, about 4 flops per add, turns O(n·eps) error into O(eps) for the total.

Failure modes and how they surface

  • Variance via E[X²] - E[X]². For readings around 1000 with spread 0.01, the two terms are ~10⁶ and their difference ~10⁻⁴: roughly ten digits gone. The result can come out negative, and a following sqrt then yields NaN. Detect by asserting variance ≥ 0 and cross-checking against Welford's one-pass algorithm or a two-pass computation. Cost: a monitoring pipeline silently emits NaN or negative jitter.
  • Residual r = b - Ax in an iterative solver when Ax ≈ b. Cancellation destroys the residual, so the solver stalls or declares false convergence. Detect by watching ||r|| stagnate and recomputing the residual in extended precision or with compensated dot products. Cost: a wrong answer returned as converged.
  • Near-parallel line/ray intersection. The 2×2 determinant is the denominator and is near zero. Detect by comparing |det| against the product of the row norms: that ratio is the condition number. Cost: jittery intersection points, objects falling through floors.
  • Summing signed financial amounts to a near-zero balance. The residual is pure noise. Detect by reconciling against decimal arithmetic. Cost: books that fail to balance by a few cents.
ApproachCostUse when
Conjugate / Vieta reformulation0 extra flops, often fewerClosed-form expression with a known cancellation
expm1 / log1p~1 function calle^x - 1 or ln(1 + x) near 0
Kahan / Neumaier summation~4 flops per addLong sums, dot products, residuals
Extended or arbitrary precision (double-double, MPFR, decimal)10×–100×Verification, or when no reformulation exists

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How do you use the 2D cross product to determine whether three points turn clockwise, counter-clockwise, or are collinear?

Answer

To determine the orientation of an ordered triplet of 2D points $A(x_1, y_1)$, $B(x_2, y_2)$, and $C(x_3, y_3)$, you evaluate the sign of the 2D cross product (the $z$-component of the 3D cross product) of the vectors $\vec{AB}$ and $\vec{AC}$.

Formula and Derivation

Translate point $A$ to the origin to form two displacement vectors: $$\vec{u} = \vec{AB} = (x_2 - x_1, y_2 - y_1)$$ $$\vec{v} = \vec{AC} = (x_3 - x_1, y_3 - y_1)$$

The 2D cross product is equivalent to the determinant of the $2 \times 2$ matrix formed by these vectors: $$\vec{u} \times \vec{v} = u_x v_y - u_y v_x = (x_2 - x_1)(y_3 - y_1) - (y_2 - y_1)(x_3 - x_1)$$

Orientation Rules (Standard Cartesian Coordinates)

Assuming the standard Cartesian coordinate system (where $x$ increases to the right and $y$ increases upwards):

  • $\vec{u} \times \vec{v} > 0$: Counter-clockwise turn (left turn at $B$).
  • $\vec{u} \times \vec{v} < 0$: Clockwise turn (right turn at $B$).
  • $\vec{u} \times \vec{v} = 0$: Collinear (the points lie on the same straight line).

(Note: In screen/graphics coordinate spaces where $y$ points downwards, the geometric interpretation of the signs inverts: positive is clockwise and negative is counter-clockwise.)

Python Implementation

Python
def orientation(a: tuple[int, int], b: tuple[int, int], c: tuple[int, int]) -> int:
    """
    Returns:
      > 0 if A -> B -> C forms a counter-clockwise turn (left turn),
      < 0 if A -> B -> C forms a clockwise turn (right turn),
      0 if points are collinear.
    """
    val = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
    return val

# Trace examples:
p1, p2, p3 = (0, 0), (4, 4), (1, 3)
# u = (4, 4), v = (1, 3)
# cross = 4*3 - 4*1 = 12 - 4 = 8 (> 0: Counter-clockwise / Left turn)

p4 = (5, 2)
# u = (4, 4), v = (5, 2)
# cross = 4*2 - 4*5 = 8 - 20 = -12 (< 0: Clockwise / Right turn)

p5 = (2, 2)
# u = (4, 4), v = (2, 2)
# cross = 4*2 - 4*2 = 8 - 8 = 0 (Collinear)

Why this beats slope comparison and angles

  1. No Division by Zero: Comparing slopes requires $\frac{y_2 - y_1}{x_2 - x_1} \lessgtr \frac{y_3 - y_1}{x_3 - x_1}$. When lines are vertical ($x_2 = x_1$ or $x_3 = x_1$), slope calculation divides by zero, requiring special branching. Cross multiplication clears denominators and removes all singularities.
  2. Avoids Floating-Point Drift: Evaluating $\text{atan2}$ or floating-point division causes catastrophic precision loss when points are near-collinear. In integer coordinates, the determinant is computed strictly via additions and multiplications, remaining completely exact.
  3. Overflow Consideration: Multiplying two 32-bit coordinates can produce a product up to $\approx 2^{63}$ in the cross-product difference. When using fixed-width types (C/C++ int32_t), intermediate values must be cast to int64_t to avoid signed overflow undefined behavior.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15

How would you explain polygon area without using the usual slogan?

Answer

The 90-second version

Picture each edge as the top of a trapezoid whose base sits on the x-axis. The trapezoid under the edge from (x_i, y_i) to (x_{i+1}, y_{i+1}) has signed area (x_i − x_{i+1})(y_i + y_{i+1})/2. Walk the boundary once and add them up. Any strip of the x-axis region that lies outside the polygon gets covered twice with opposite signs (once travelling right, once coming back) so it cancels. What survives is exactly the enclosed region. That is the whole idea; the "shoelace" name is just what the algebra looks like once you expand the trapezoid sum.

Expanding gives A = ½ Σ (x_i·y_{i+1} − x_{i+1}·y_i). The sign is the winding direction: positive counter-clockwise, negative clockwise, zero for a degenerate or self-cancelling path. In integer coordinates the sum is exact before the final halving, so you can keep the doubled value as an integer and only divide when you need the area itself.

Python
def signed_area2(pts):                      # twice the signed area, exact in integers
    n = len(pts)
    return sum(pts[i][0]*pts[(i+1) % n][1] - pts[(i+1) % n][0]*pts[i][1]
               for i in range(n))

signed_area2([(0,0), (4,0), (4,3), (0,3)])  # 24 -> area 12, counter-clockwise

The trapezoid sum, traced on the same square

edge(x_i − x_{i+1})(y_i + y_{i+1})/2
(0,0)→(4,0)(0−4)(0+0)/2 = 0
(4,0)→(4,3)(4−4)(0+3)/2 = 0
(4,3)→(0,3)(4−0)(3+3)/2 = 12
(0,3)→(0,0)(0−0)(3+0)/2 = 0
sum12

Same 12, reached without ever naming the formula.

Alternatives, and when each wins

  • Triangulation from a fixed vertex is O(n) for a convex polygon but needs ear-clipping (O(n²), or O(n log n) with a good implementation) once the polygon is non-convex. The trapezoid walk handles any simple polygon in one O(n) pass, which is why it is the default.
  • Green's theorem is the continuous parent: the shoelace sum is its discretisation, so the same reasoning extends to curved boundaries.
  • Signed vs absolute area: keep the sign when you need orientation. Point-in-polygon, convex hull, winding number. Take the absolute value only at the very end, when the caller genuinely wants a magnitude.

Failure modes

  • Taking abs() early throws away orientation that downstream code depends on. It survives casual testing because a single convex test polygon never exposes it.
  • Floating-point coordinates far from the origin lose precision through cancellation; translate the polygon so its centroid is near (0,0) before summing.
  • A self-intersecting path returns the algebraic area, lobes of opposite winding cancel, not the area a human would measure. If you need the union area of a self-overlapping shape, this is the wrong tool; reach for a polygon-clipping library instead.
  • Duplicate or collinear vertices are harmless (they contribute zero), but a repeated first/last vertex must not be counted twice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of point in polygon?

Answer

The failure I inject: a point whose ray passes exactly through a vertex.

Hand the team this polygon and point:

poly = [(0,0), (2,2), (0,4), (4,4), (4,0)]   # square with a triangular notch cut from the left
pt   = (1,2)

The correct answer is outside. The point sits inside the notch triangle (0,0)-(2,2)-(0,4), which is not part of the polygon.

Why it is a good probe: the ray from (1,2) going right at y=2 meets the boundary at the vertex (2,2) and again at x=4. The vertex is a pass-through (one incident edge drops to (0,0), the other rises to (0,4)) so it is one crossing, not two. Two crossings to the right → even → outside.

A naive implementation that tests y1 <= y <= y2 (or otherwise counts both incident edges) counts the vertex twice: 3 crossings → odd → inside. Wrong. The bug is invisible on random points and only fires when the ray lands exactly on a vertex, which is why it survives casual testing.

The fix is the half-open rule: count an edge only when the ray's y is in [min(y1,y2), max(y1,y2)), i.e. (y1 > y) != (y2 > y). That counts a pass-through vertex once and a local extremum zero times.

Python
def inside(pt, poly):
    x, y, c = pt[0], pt[1], False
    for (x1,y1), (x2,y2) in zip(poly, poly[1:] + poly[:1]):
        if (y1 > y) != (y2 > y):                       # half-open in y
            if x < (x2-x1)*(y-y1)/(y2-y1) + x1: c = not c
    return c

Trace on the case above: edge (2,2)-(0,4) fires (2>2 is False, 4>2 is True), intersection x=2, 1<2 → flip to inside. Edge (4,4)-(4,0) fires, intersection x=4, 1<4 → flip to outside. Edge (0,0)-(2,2) does not fire (0>2 and 2>2 are both False). Result: outside. Correct.

How to check understanding. Ask them to predict the output before running it, then to explain why the vertex counts once. A strong answer names the half-open convention and separates two questions: (a) parity of crossings, (b) what "on the boundary" means. A weak answer says "floating point" and reaches for an epsilon, which does not fix a double-counted vertex.

The boundary case is a separate decision. A point exactly on an edge or vertex is undefined by the parity rule. Pick a convention, strict interior vs interior-or-boundary, and document it. Shapely exposes exactly this split (contains vs covers); PostGIS has ST_Contains vs ST_Covers. If you need exact predicates near vertices, use robust orientation tests (Shewchuk's adaptive predicates) rather than a hand-tuned epsilon, which trades robustness for a magic constant.

Alternatives. Winding number is O(n) too and gives a signed count; it handles self-intersecting polygons differently and still needs a boundary convention, so it is not a free upgrade. For production, prefer a tested library primitive (Shapely, CGAL, PostGIS) unless you have a measured reason to hand-roll: the vertex and boundary cases are exactly where hand-rolled code fails.

Other failures worth injecting: a horizontal edge collinear with the ray; a point exactly on a vertex; a degenerate polygon (duplicate or collinear vertices, zero area). Detect them with a fixed regression suite of these cases plus property-based tests against a reference implementation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do you detect whether two 2D line segments intersect, and how do you handle edge cases such as collinearity and bounding-box overlap?

Answer

Two 2D segments $AB$ and $CD$ intersect if and only if each segment straddles the line containing the other, or if they are collinear and their 1D projections overlap.

1. Orientation Predicate via 2D Cross Product

Given three points $P, Q, R$, the 2D cross product of $\vec{PQ}$ and $\vec{PR}$ determines the orientation: $$ \text{orient}(P, Q, R) = (Q_x - P_x)(R_y - P_y) - (Q_y - P_y)(R_x - P_x) $$

  • $> 0$: Counter-clockwise (left turn)
  • $< 0$: Clockwise (right turn)
  • $= 0$: Collinear

For non-collinear segments to intersect, $C$ and $D$ must lie on opposite sides of line $AB$ (or on it), and $A$ and $B$ must lie on opposite sides of line $CD$ (or on it): $$ \text{sign}(\text{orient}(A, B, C)) \neq \text{sign}(\text{orient}(A, B, D)) \quad \text{and} \quad \text{sign}(\text{orient}(C, D, A)) \neq \text{sign}(\text{orient}(C, D, B)) $$

2. Collinear and Degenerate Overlap

When three or four points are collinear, orientation alone is insufficient. A cross product of zero indicates points lie on the same infinite line, not that the segments physically touch. To resolve collinearity:

  1. Quick-reject via Axis-Aligned Bounding Box (AABB) intersection: segments can only intersect if their intervals overlap along both $X$ and $Y$.
  2. If bounding boxes overlap and $\text{orient}(A, B, C) = 0$, $C$ lies on segment $AB$ if and only if $\min(A_x, B_x) \le C_x \le \max(A_x, B_x)$ and $\min(A_y, B_y) \le C_y \le \max(A_y, B_y)$.

3. Implementation

Python
def orient(p, q, r):
    val = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
    return (val > 0) - (val < 0)  # +1 (CCW), -1 (CW), 0 (collinear)

def on_segment(p, q, r):
    # Assumes collinearity; checks if q is on segment pr
    return (min(p[0], r[0]) <= q[0] <= max(p[0], r[0]) and
            min(p[1], r[1]) <= q[1] <= max(p[1], r[1]))

def segments_intersect(a, b, c, d):
    # Step 1: Bounding-box check (fast rejection and collinear guard)
    if max(a[0], b[0]) < min(c[0], d[0]) or min(a[0], b[0]) > max(c[0], d[0]):
        return False
    if max(a[1], b[1]) < min(c[1], d[1]) or min(a[1], b[1]) > max(c[1], d[1]):
        return False

    # Step 2: Orientation tests
    d1 = orient(c, d, a)
    d2 = orient(c, d, b)
    d3 = orient(a, b, c)
    d4 = orient(a, b, d)

    # General straddle condition
    if ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and \
       ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0)):
        return True

    # Collinear/touching boundary points
    if d1 == 0 and on_segment(c, a, d): return True
    if d2 == 0 and on_segment(c, b, d): return True
    if d3 == 0 and on_segment(a, c, b): return True
    if d4 == 0 and on_segment(a, d, b): return True

    return False

Complexity and Numeric Pitfalls

  • Time Complexity: $O(1)$ evaluations, no divisions or square roots.
  • Numeric Robustness: Using standard IEEE 754 floats introduces rounding where orient(...) == 0 almost never triggers or flips sign erroneously on near-collinear inputs. Exact integer coordinates or arbitrary-precision arithmetic (such as Python integers) avoid floating-point drift entirely.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do floating-point representation limits and rounding errors impact geometric predicates, and how do you achieve numerical robustness with epsilon comparisons or exact arithmetic?

Answer

Floating-point numbers in standard IEEE 754 double precision (binary64) have 53 bits of significand. Geometric predicates evaluate signs of algebraic expressions, such as the 2D cross product or orientation determinant:

$$\det(A, B, C) = (B_x - A_x)(C_y - A_y) - (B_y - A_y)(C_x - A_x)$$

When points are nearly collinear, $(B_x - A_x)(C_y - A_y)$ and $(B_y - A_y)(C_x - A_x)$ are almost equal. Subtracting them causes catastrophic cancellation. The rounding errors in computing the products and their difference can flip the sign or return zero when the true geometric orientation is non-zero, or vice-versa.

The Failure Mode: Topological Inconsistency

The fundamental risk is not just numerical noise; it is breaking algebraic invariants that algorithms assume:

  1. Non-transitivity: Floating-point cross products can report that point $A$ is to the left of directed line $BC$, $B$ is to the left of $CA$, and $C$ is to the left of $AB$ simultaneously, creating an impossible cycle.
  2. Inconsistent line intersections: In algorithms like the Bentley-Ottmann sweep-line, computing an intersection using floating-point coordinates and inserting it into the event queue can place the intersection point behind the sweep line due to roundoff, resulting in infinite loops, missed intersections, or invalid pointer dereferences.
  3. Degenerate convex hulls: In Graham scan or Quickhull, an incorrect sign check can incorrectly delete valid vertices or produce self-intersecting polygons.

Mitigation 1: Epsilon (Tolerance) Comparisons

A common heuristic is replacing exact zero with an absolute or relative tolerance:

Python
def orientation_epsilon(ax, ay, bx, by, cx, cy, eps=1e-9):
    det = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax)
    if abs(det) <= eps:
        return 0  # Collinear / degenerate
    return 1 if det > 0 else -1

Trade-off: Epsilon does not restore topological consistency. If $|det| \le \varepsilon$ is classified as collinear, the predicate becomes non-transitive: $A$ can be collinear with $B$, and $B$ collinear with $C$, while $A$ and $C$ are not collinear. Choosing $\varepsilon$ is scale-dependent: an absolute tolerance fails if coordinates scale by $10^6$ or $10^{-6}$.

Mitigation 2: Exact Geometric Predicates and Integer Arithmetic

  1. Fixed-Point / Exact Integers: If input coordinates are bounded integers (e.g., coordinates fit in 24 bits), intermediate determinant products require at most 49 bits, which fits comfortably in a standard 64-bit signed integer (int64_t). For arbitrary-precision integers (like Python int), operations are exact with modest memory overhead.
  2. Adaptive Floating-Point Filters (Shewchuk's predicates): Evaluate using standard IEEE 754 doubles while maintaining rigorous error bounds. If the computed value is larger than the maximum possible rounding error bound, its sign is guaranteed correct ($O(1)$ time). Only if the determinant falls within the error bound does the predicate fall back to exact arbitrary-precision arithmetic (expansion arithmetic).
StrategyTime OverheadCorrectness GuaranteeScale Sensitivity
Raw IEEE 754$O(1)$ (Baseline)Flips signs, violates topologyHigh (catastrophic cancellation)
Epsilon Tolerance$O(1)$ (Low)Violates transitivity; tuning requiredHigh (fails across dynamic scales)
Scaled Integers$O(1)$ if within bit bounds100% exact signNone (scale fixed in advance)
Adaptive Predicates$O(1)$ average, $O(K)$ worst100% exact signNone (exact sign verified)

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Walk me through making a 2D orientation predicate exact for integer inputs: how you represent coordinates, compare cross products without division, and order a bounding-box rejection before the multiply-heavy test.

Answer

Representation. Keep coordinates as integers. For a point P store (Px, Py) exactly: Python ints, or a fixed-width type sized to the range. If the input is rational, put every coordinate over one common positive denominator D: Px = PX/D, Py = PY/D with PX, PY, D integers and D > 0. A single D shared by all points keeps the arithmetic integral.

The predicate. The orientation of A, B, C is the sign of the 2×2 determinant

orient(A,B,C) = (Bx−Ax)(Cy−Ay) − (By−Ay)(Cx−Ax).

Positive means C is left of the directed line A→B, negative means right, zero means collinear. With integer coordinates every factor is an integer, so the determinant is an integer and its sign is exact: no epsilon, no division.

For rationals, substitute Px = PX/D:

orient = [ (BX−AX)(CY−AY) − (BY−AY)(CX−AX) ] / D².

D² > 0, so the sign of the integer numerator is the sign of the true determinant. You never divide; you compare the numerator against zero. That is the whole trick. Comparing slopes or using atan2 introduces rounding and loses the sign exactly when the determinant is tiny relative to the coordinates: the case that matters.

Ordering the test. For segment intersection, reject with an axis-aligned bounding box before touching the determinant. AB and CD cannot meet if

max(Ax,Bx) < min(Cx,Dx) or max(Cx,Dx) < min(Ax,Bx), or the same on y.

That is four comparisons and zero multiplications. Only when the boxes overlap do you compute the four orientations. The box is the cheap filter; the determinants are the expensive part, and for spatially separated inputs most pairs die on the box.

Code (Python 3; int is arbitrary precision):

Python
def orient(a, b, c):
    return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])

def sgn(x):
    return (x > 0) - (x < 0)

def on_segment(a, b, p):          # p assumed collinear with a, b
    return (min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and
            min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))

def seg_intersect(a, b, c, d):
    if max(a[0], b[0]) < min(c[0], d[0]) or max(c[0], d[0]) < min(a[0], b[0]):
        return False
    if max(a[1], b[1]) < min(c[1], d[1]) or max(c[1], d[1]) < min(a[1], b[1]):
        return False
    o1, o2 = orient(a, b, c), orient(a, b, d)
    o3, o4 = orient(c, d, a), orient(c, d, b)
    if o1 == 0 and on_segment(a, b, c): return True
    if o2 == 0 and on_segment(a, b, d): return True
    if o3 == 0 and on_segment(c, d, a): return True
    if o4 == 0 and on_segment(c, d, b): return True
    return sgn(o1) * sgn(o2) < 0 and sgn(o3) * sgn(o4) < 0

The last line must be a strict sign product, not (o1 > 0) != (o2 > 0). That form treats a zero as negative and reports an intersection when a collinear endpoint lies off the other segment. Trace A=(0,0), B=(1,0), C=(2,0), D=(0,1): the boxes overlap, so the determinants run. o1 = orient(A,B,C) = (1)(0) − (0)(2) = 0: C is on line AB but past B. o2 = orient(A,B,D) = (1)(1) − (0)(0) = 1. o3 = orient(C,D,A) = (−2)(0) − (1)(−2) = 2. o4 = orient(C,D,B) = (−2)(0) − (1)(−1) = 1. The collinear guards all fail because C is not on segment AB. sgn(0)·sgn(1) = 0, not < 0, so the function returns False: correct, the segments miss. The != form would have returned True.

Bit widths. For signed 32-bit coordinates, differences need 33 bits, a product of two differences needs 65 bits, and the difference of two products needs 66 bits, so int64 overflows and you want 128-bit (or Python ints). For signed 64-bit coordinates, differences need 65 bits, products 129 bits, and the final difference 130 bits, so __int128 is not enough; use arbitrary precision or a 130-bit type.

Non-integer inputs. If a float is exactly integral (3.0), int() is exact. If it is 1.0000000001 from a measurement, no exact integer exists to recover. Parse the original decimal string as Fraction/Decimal when you have it; otherwise pick a tolerance, snap to a grid, and document that snapping can manufacture false collinearity or false intersections. Epsilon belongs to float inputs; an exact integer predicate never uses one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

A vendor promises the cross product and orientation is handled for you. What do you still own?

Answer

You own everything the predicate's sign is used to decide, and the exactness of the sign itself. The vendor owns one function: given three points, return the sign of the orientation determinant. That is a building block, not an algorithm, and it is only as trustworthy as the arithmetic behind it and the inputs you hand it.

Concretely, four things stay with you.

1. The input contract. The predicate is exact only for the points it actually receives. If your coordinates are float64 and you computed them by transforming or scaling, the rounding happened before the call. orient2d cannot recover a point that was already snapped. You own whether inputs are exact integers, fixed-point, or floats, and you own the units and handedness.

2. The sign convention. A vendor's orient2d returns positive for counter-clockwise in a right-handed frame. Screen coordinates are y-down, so the same three points flip sign. Nothing in the API tells you which convention it uses; you read the docs or you test it. Getting this wrong inverts every hull, winding, and containment decision downstream.

3. Degenerate cases. The predicate returns 0 for collinear points. It does not tell you what collinearity means for your algorithm: a zero-length segment, a duplicate vertex, a point exactly on an edge in a point-in-polygon test. You own that policy.

4. The algorithm on top. Sweep-line ordering, hull construction, winding rules, tie-breaking when two events share a coordinate: none of that is in the predicate.

The exactness question is the one that bites. A naive determinant is two multiplications and a subtraction:

Python
def orient(a, b, c):
    return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])

Trace it on three exactly-representable integer points: a=(0,0), b=(2**30, 2**30+1), c=(2**30+1, 2**30+2).

  • True value: 2**30*(2**30+2) - (2**30+1)**2 = (2**60 + 2**31) - (2**60 + 2**31 + 1) = -1. Clockwise.
  • (b[0]-a[0])*(c[1]-a[1]) = 2**30 * (2**30+2) = 2**60 + 2**31, a multiple of 256, exact.
  • (b[1]-a[1])*(c[0]-a[0]) = (2**30+1)**2 = 2**60 + 2**31 + 1. Near 2**60 the spacing between floats is 256, so this rounds to 2**60 + 2**31.
  • Difference: 0. The predicate reports collinear; the points are not.

So the vendor's guarantee is only as strong as its arithmetic. Filtered exact predicates (Shewchuk's adaptive orient2d (1997), the robust-predicates port, CGAL's Exact_predicates_inexact_constructions_kernel) compute the sign exactly, using a fast floating-point filter and falling back to exact expansion arithmetic only when the filter is inconclusive. That fallback is the cost you are buying.

When to wrap or replace. If the vendor's predicate is a plain float determinant, wrap it with an exact one for any near-degenerate input, or replace it outright. If it is already filtered-exact, keep it and own the four items above. The decision turns on whether your inputs can be near-collinear at a scale where the products exceed 2**53, if they can, a float determinant is not a guarantee, it is a coin flip on the cases that matter most.

Failure mode to watch. The bug does not appear on random points; it appears on the near-degenerate ones your algorithm is specifically built to resolve. Detect it by running the predicate against an exact reference on adversarial inputs, points on a line perturbed by one ulp, not by load testing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

When would you refuse a design because of segment intersection?

Answer

I'd refuse in two situations: when the design's correctness rests on an orientation sign its coordinate type cannot compute reliably, and when its cost model assumes pairwise testing at a scale that won't finish. Everything else is negotiable.

State the assumptions that decide it: coordinate type and magnitude, segment count n, expected intersection count k, and whether the design needs a boolean predicate or the intersection points themselves.

Refusal 1: float coordinates with a topology-critical predicate. Orientation is the sign of a cross product. With coordinates bounded by M, the computed value carries absolute error on the order of eps·M². For M = 1e6 in IEEE-754 double (eps ≈ 2.2e-16) that is roughly 1e-4. Any true cross product below that is noise, and the sign is arbitrary. A design that branches on cross < 0 with no tolerance, over inputs that include near-collinear segments (map overlay, CAD, polygon booleans) is wrong on exactly the inputs that matter. Refuse it, or require exact predicates (Shewchuk's adaptive orientation, or CGAL's exact kernel).

Python
# Python 3.12, integer coordinates
def cross(o, a, b):
    return (a[0]-o[0])*(b[1]-o[1]) - (a[1]-o[1])*(b[0]-o[0])

def proper_intersect(p1, p2, p3, p4):
    d1 = cross(p3, p4, p1)
    d2 = cross(p3, p4, p2)
    d3 = cross(p1, p2, p3)
    d4 = cross(p1, p2, p4)
    return d1*d2 < 0 and d3*d4 < 0

Trace: p1=(0,0), p2=(4,4), p3=(0,4), p4=(4,0) gives d1=-16, d2=16, d3=16, d4=-16, so it returns True. The diagonals cross at (2,2). Now p1=(0,0), p2=(4,0), p3=(2,0), p4=(6,0): d1=d2=0, so it returns False, even though the segments overlap on [2,4]. That missed collinear case is the second thing I check for in a design.

Refusal 2: O(n²) at a scale that doesn't fit. Brute force is n(n-1)/2 pair tests. At n = 100,000 that's ~5e9 tests; at ~10 ns each, ~50 s. A sweep line (Bentley–Ottmann) is O((n+k) log n) in the number of intersections k: with k = 1,000 that's ~1.7e6 event steps, milliseconds. If the design says "check every pair" and n is five figures, refuse it.

ApproachCostUse when
PairwiseO(n²)n ≤ a few thousand
Sweep lineO((n+k) log n)many segments, sparse intersections
Exact libraryO(n²) or sweep, exactfloat coords, topology-critical

What I'd accept instead. Integer coordinates within 2^53 (exact in double), n small enough for pairwise, or a library that owns the predicate. And the design must have a stated answer for degeneracies: collinear overlap, shared endpoints, vertical segments in a sweep (event ordering breaks). If it has none, that's the refusal.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names convex hulls as the cause?

Answer

An alert that names convex hulls is telling you where someone guessed the problem is, not where it is. Treat the algorithm name as a hypothesis to falsify in the first five minutes, not as a place to start reading code. The name in the alert is itself a smell: a good alert names the symptom (p99 of the endpoint, error rate, queue depth), not the suspected cause. Fixing that is part of the follow-up.

Three questions, in order:

  1. Is it real and user-visible? Check the SLO the alert is attached to: p99 latency of the endpoint that calls the hull, its error rate, or the depth of the queue behind it. If the alert is a CPU-utilisation threshold with no user impact, you have a noisy alert, not an incident.
  2. Is the hull the bottleneck or a symptom? The hull is usually one span inside a request that also does I/O, deserialisation and a database query. Read the span breakdown for that request before touching hull code.
  3. What changed? Input size, input distribution, or the code path. Hull cost is dominated by the sort, so the thing that moves it is n.

Why hull cost moves. Andrew's monotone chain is O(n log n) and the sort is essentially the whole cost; the two scan passes are O(n). Latency therefore scales with the number of points, not with the shape. Two operational traps:

  • n grows silently. A query that returned 10k points now returns 1M because an upstream filter was dropped or a tenant's data grew. 100× the points is roughly 150× the sort work, since n log n grows faster than n.
  • Degenerate inputs. An all-collinear or all-duplicate point set makes the hull a segment or a single point. Implementations that assume a 2D area can return empty, loop, or divide by zero. That surfaces as errors, not latency.

Hypothetical arithmetic: if p99 is 40 ms at 10k points, the sort term predicts about 40 ms × (1M·log 1M)/(10k·log 10k) ≈ 40 ms × 150 ≈ 6 s at 1M points. That is the shape of the incident: a step change, not a slow drift.

Alert saysLikely real causeFirst check
hull p99 > 500 msn grewpoint-count histogram for the last hour
hull error rate updegenerate input (collinear/duplicate)sample failing payloads, look for zero-area
hull CPU saturatedcalled in a loop (per-frame/per-query)call count per request, not per-call cost
hull timeoutupstream unbounded result setthe query feeding the hull

Mitigate now vs. fix later. Mitigate: cap n (sample or bound the result set), disable the feature flag that added the hull path, or shed the offending tenant. Fix: bound the input at the source, add a degenerate-input guard, and re-point the alert at input size rather than hull latency so the next page names the cause.

Failure modes to name.

  • The alert names the hull but the cause is upstream: an unbounded query. Capping the hull hides it until the query grows again.
  • Floating-point precision: near-collinear points can flip the orientation predicate, giving output that is unstable across runs. Non-deterministic hull output is the predicate, not load.
  • The alert is a threshold on a proxy metric with no user impact. Close it as noise and fix the alert rather than the hull.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

What belongs in a runbook section on closest pair of points, and what does not?

Answer

The section is the call site's operational contract, not a description of the algorithm. Concrete case: a nightly batch runs closest-pair over 10^6 float64 2-D points, offline, exact answer required, no insertions.

The code the section documents (Python 3.12):

Python
CUTOFF = 64  # brute force at or below this size

def closest_pair(pts):
    px = sorted(pts)                      # x-order, once
    py = sorted(pts, key=lambda p: p[1])  # y-order, maintained by merge
    return _rec(px, py)

def _rec(px, py):
    n = len(px)
    if n <= CUTOFF:
        return _brute(px)                 # O(n^2) scan
    mid = n // 2
    midx = px[mid][0]
    left = set(px[:mid])
    ly = [p for p in py if p in left]
    ry = [p for p in py if p not in left]
    d = min(_rec(px[:mid], ly), _rec(px[mid:], ry))
    strip = [p for p in py if abs(p[0] - midx) < d]
    for i, p in enumerate(strip):
        for q in strip[i+1:i+8]:          # at most 7 ahead
            d = min(d, _dist(p, q))
    return d

Four blocks go in, nothing else.

Preconditions. Points sorted by x once up front; the strip kept in y-order across recursion levels; duplicates removed upstream; exact arithmetic, no epsilon. Each failing gives a silently wrong answer, so they are preconditions, not background.

Knobs and current values. CUTOFF = 64, a placeholder to re-measure: on the box used here the crossover moved by roughly ±10 with CPU generation and coordinate type. Plus the recursion-depth cap that aborts a degenerate split to brute force. Both are per-batch overrides, not deploys.

Signals, thresholds, actions.

SignalExpectedAction when off
Time ratio n=10^4 → n=10^6, same box~150 (n log n)~225: strip re-sorted per level. Merge the halves' y-lists. ~10,000: split degenerated, run is quadratic
Recursion depth~log2(10^6) = 20Latency cliff on one batch or stack overflow: split on the wider-spread axis, or trip the depth cap
Mismatch count vs nightly brute force, 1% sampleexactly 0Non-zero pages the owner: correctness bug. Freeze the cutoff, re-run the golden set
Stage p99baselineInvestigate before the next batch window

Worked trace of the strip step, five points, CUTOFF=4: (0,0), (3,0), (4,0), (5,2), (7,0).

px = (0,0),(3,0),(4,0),(5,2),(7,0); mid=2, midx=4. Left {(0,0),(3,0)} → dl=3. Right {(4,0),(5,2),(7,0)} → dr=√5≈2.236. d=2.236. py = (0,0),(3,0),(4,0),(7,0),(5,2); strip = points with |x−4| < 2.236 → (3,0),(4,0),(5,2). Compare: (3,0)-(4,0)=1 → d=1; (3,0)-(5,2)=2.828; (4,0)-(5,2)=2.236. Return 1.0. The cross pair (3,0)-(4,0) is the answer, and only the strip finds it.

What does not belong. The recurrence T(n)=2T(n/2)+O(n) and its O(n log n) solution; the full 8-square packing proof; a "what is closest pair of points" primer; a past incident's narrative without the rule it generalises to. One line of the packing fact stays, because a knob and the cross-check rest on it: within distance d of the split line the candidate window is 2d wide and d tall; cut into d/2 squares that is 8 cells, each holding at most one point, since two points in one cell are at most (d/2)·√2 = 0.707d apart. So at most 7 comparisons per point and the merge is linear. The proof stays out; the number stays in.

Alternatives and their failure modes. Below the cutoff brute force wins on constants, not asymptotics. Above it, divide and conquer wants the whole point set in hand; if points arrive incrementally, a sweep line is also O(n log n) and avoids re-sorting the batch. Grid hashing with cell side near d is O(n) expected on near-uniform data and parallelises cleanly, but one dense cluster (10^4 points inside a single cell) pushes it back to O(n^2), and two coincident points give d=0, a cell side of 0, and NaN distances instead of a merely wrong finite one.

Three failure modes earn their own lines:

  • Degenerate split, where all points share one x or 90% do. The median split puts everything on one side and depth goes from 20 to 10^6, so the run turns quadratic. Symptom is a latency cliff on one specific batch, or a stack overflow. Detect with a recursion-depth gauge and an x-distinctness histogram; act by splitting on the axis with the larger spread, or tripping the depth cap.
  • Strip re-sorted per level: still correct, but n log^2 n. Detect by the 225-versus-150 ratio and confirm it in a profile.
  • Strip window taken in x-order instead of y-order: misses pairs, silently and consistently. Only the nightly cross-check finds it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

How would you review a pull request whose risk is avoiding square roots?

Answer

I'd review this as a correctness change first, not a performance tweak. The first question to the author: what are the coordinate types and ranges? That decides whether squared distance is exact or just a different rounding.

If coordinates are integers and the squared distance fits in the chosen integer type, the change is safe. I'd check the diff for three things: no sqrt remains in the comparison path; every threshold is squared correctly; tie-breaking is unchanged. I'd demand tests with maximum coordinates and near-equal distances.

Python
def d2(a, b):
    dx = a[0] - b[0]
    dy = a[1] - b[1]
    return dx*dx + dy*dy

# threshold: radius r
if d2(p, q) <= r*r:
    ...

For integer coordinates, this is exact. For 32-bit signed coordinates, dx*dx + dy*dy can reach about 3.7e19, which overflows a signed 64-bit integer (max 9.22e18). So I'd ask for the coordinate bound. If coordinates fit in 16 bits, int64_t is enough; if they fit in 32 bits, use __int128 or a big integer. In Python, integers are arbitrary precision, so no overflow, but the code may still be slower than needed.

If coordinates are floats, squared distance is not exact. It avoids the sqrt rounding but still rounds the squares and the sum. I'd ask for an epsilon and a tie-breaking rule. The alternative is math.hypot, which is more accurate than sqrt(dx*dx + dy*dy) and avoids overflow for large values, but it is slower. If the comparison is only for ordering, squared distance is usually fine; if it feeds a threshold, compare d2 <= r*r and be explicit about the epsilon.

ApproachExact for integers?Overflow riskWhen to use
Squared distance, integerYes, if type wide enoughYes, check boundsOrdering and integer thresholds
Squared distance, floatNoUnderflow/overflow for extreme valuesOrdering when approximate is fine
sqrt + epsilonNoNoWhen actual distance is needed
math.hypotNoNoAccurate float distance

The failure modes are concrete. Overflow in dx*dx + dy*dy can wrap and invert the comparison. A threshold left as r instead of r*r changes the radius. Tie-breaking that used sqrt may now see equal squared distances and pick a different point. Detection: run with maximum coordinates under UBSan for signed overflow; property-test that squared ordering matches high-precision sqrt for random points; benchmark only if the PR claims a performance win.

I'd approve the change if the author answers the type and range questions, the tests cover the boundaries, and the diff removes sqrt only from the comparison path. I'd keep sqrt for reporting the actual distance.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

How does cycle detection in numeric sequences interact with rollback, and where do people ignore that?

Answer

Core answer

Cycle detection rests on one assumption: the sequence is a deterministic function of its state, so the state graph is fixed and any repeated value is a genuine cycle. Rollback: restoring the generator to an earlier state, whether by a transaction abort that rewinds application state, a checkpoint restore, or deterministic replay from a snapshot: breaks that assumption. It moves the walk backwards onto states it already visited, so a repeat no longer implies a cycle. The detector has to be told the rollback happened; if it isn't, it reports cycles that don't exist.

Mechanism

The two detector families fail differently.

  • Value-keyed (hash set of seen values), O(μ+λ) memory. After a rollback the first re-visited value is already in the set, so it fires a false cycle immediately. The loop it reports is the span between the snapshot and the rollback point, not the true period.
  • Floyd/Brent (tortoise and hare), O(1) space. No set, so no stale entry to false-positive on, but the invariant that the hare sits at exactly twice the tortoise's position only holds on a single forward walk. Rewind one pointer and not the other and the comparison is meaningless: you can spin forever or exit on a coincidence.

Trace: LCG s' = (5s + 3) mod 16, s0 = 1. Hull–Dobell holds (a−1=4 divisible by 4, c odd), so the period is the full 16:

1, 8, 11, 10, 5, 12, 15, 14, 9, 0, 3, 2, 13, 4, 7, 6, 1

Snapshot at state 10 (step 3). Walk to state 9 (step 8). Roll back to the snapshot. A value-keyed detector holding {1,8,11,10,5,12,15,14,9} observes the restored state 10, finds it already present, and reports the loop 10→5→12→15→14→9→10, length 6. The true period is 16. Nothing in the emitted values tells you the report is wrong.

Where people ignore it

The database case is the one that bites. In PostgreSQL, nextval() is non-transactional: a rolled-back transaction does not return the sequence value, so you get gaps, not repeats. Teams that assume rollback rewinds the sequence build dedup or cycle logic that never fires, or read a gap as evidence of a cycle. The mirror error is assuming a sequence is monotone and gap-free, then treating a legitimate wrap as corruption.

Fix

Detect on the generator's internal state, not on emitted values, and make rollback an explicit event that resets the detector: clear the set, restart both pointers. Better, make the sequence a pure function of an immutable input (seed plus step index) so there is no state to roll back and the graph is fixed by construction. If you can't, log the rollback together with the state it restored to; a cycle report without that context is unverifiable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you document stating numeric assumptions so the next owner can operate it?

Answer

For each number a function takes or returns, write down three things: its domain (range and sign), its unit (or explicitly none), and its tolerance together with the sample size that tolerance holds for. Put each one in the layer that fails when the assumption breaks, and keep the only copy in code, not in a wiki.

The layers, cheapest first:

  • Docstring: the contract a human reads and a reviewer diffs.
  • Boundary assertion: the domain, so a violating call raises instead of returning a plausible wrong number.
  • Tests: the edge cases the domain names - zero, the maximum, a negative, a NaN.
  • A short design note or ADR: the reasoning behind a non-obvious bound, so the next owner does not widen it blind.

A documented contract (Python 3.12):

Python
def midpoint(a: int, b: int) -> int:
    """Midpoint of the closed interval [a, b].

    Domain:    0 <= a <= b <= 2**63 - 1   (enforced below)
    Unit:      none - an element index, not bytes or seconds
    Guarantee: floor((a + b) / 2); not round-half-up.
    Raises:    ValueError outside the domain.
    Not defined for a < 0: floor division rounds toward -inf, so (-3, 2) -> -1.

    The 2**63 - 1 bound is not a Python limit; ints are arbitrary precision.
    It is written down because this expression gets copied into C and Java,
    where a + b overflows a signed 64-bit int at a = b = 2**63 - 1.
    a + (b - a) // 2 does not.
    """
    if not 0 <= a <= b <= 2**63 - 1:
        raise ValueError(f'domain 0 <= a <= b <= 2**63-1: a={a}, b={b}')
    return a + (b - a) // 2

Three traced cases become the tests:

  • midpoint(0, 10): b - a = 10, 10 // 2 = 5, 0 + 5 = 5. Exact.
  • midpoint(263 - 2, 263 - 1): b - a = 1, 1 // 2 = 0, returns 9223372036854775806, still inside the domain. The obvious a + b would be 18446744073709551613 and overflow a signed 64-bit int.
  • midpoint(-3, 2): the guard fails and raises. Without it the return is -3 + 5 // 2 = -1, a silent wrong answer for a caller who wanted 0.

What each layer catches, and how it drifts:

LayerCatchesCostDrifts when
DocstringA human re-reading before a changeFreeNobody updates it when the code moves
Boundary assertionBad values at run time, at the call boundaryOne comparison per callStripped from hot loops, or debug-only builds
Type contract (newtype, Annotated, range type)Unit mix-ups and out-of-range values at construction or compileRefactor of call sitesEscaped with an unchecked cast
Property test (Hypothesis, QuickCheck)Edges nobody enumeratedCI minutesTolerance loosened to make a flake pass
ADR / module noteWhy the bound or tolerance is what it isHalf a pageThe number changes and the note does not

Floating point needs the tolerance and the sample size together. Double unit roundoff is u = eps / 2, about 1.11e-16, so naive summation of n = 1e6 values carries a worst-case relative error near (n - 1) u = 1.1e-10 measured against the sum of absolute values. 'Tolerance 1e-9' is defensible at that n; '1e-12' is not, and retrying does not fix it. Write the tolerance as a function of n and the input range, or the next owner will tighten it and chase flakes.

Failure modes and how they surface: an unstated sign domain gives silent wrong answers that only a negative-input test exposes; a missing unit gives results off by 1000 (milliseconds against seconds - the 1999 Mars Climate Orbiter was lost to pound-force-seconds against newton-seconds); a tolerance tightened without re-measuring shows up as a CI flake rate that tracks machine load, not as a diff.

What I would not do: assert inside a per-element inner loop, where the check costs a branch per element - validate once at the entry point instead.

Curated: · Written: · Reviewed:

Difficulty: Hard