Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Stress Testing & Debugging Algorithms

Brute-force oracles, random tests, edge cases and invariant checks.

Your solution passes the samples and fails hidden test 37, and the judge will never show you test 37. So become your own judge: a slow solution you trust, a generator of small random inputs, and a loop that compares the two. Then shrink the first failure until the bug has nowhere left to hide.

What you’ll learn

  • Build a stress test from an oracle, a generator and a comparison loop, and shrink a failing input to a minimal one.
  • Prove how many random tests catch a bug that a fraction pp of inputs trigger, and explain why small inputs catch most bugs.
  • Use properties, invariant assertions, edge-case checklists and adversarial inputs, which need no oracle at all.
  • Verify answers faster than recomputing them, with Freivalds's algorithm and with certifying algorithms.

Oracle, generator, loop

A stress test has three parts.

  • An oracle: a second solution that is obviously correct, usually the brute force. Speed does not matter, since it only ever sees tiny inputs; an O(n3)O(n^3) or exponential oracle is fine.
  • A generator of small random inputs with small values, so that duplicates, zeros, negative numbers and ties, the raw material of edge cases, appear constantly.
  • A loop that runs both solutions and stops at the first disagreement.

Here it is against a classic slip: Kadane's maximum-subarray algorithm with its running best initialized to 0.

python
import random

def max_subarray_buggy(a):         # Kadane, but best starts at 0: wrong if every value is negative
    best = cur = 0
    for x in a:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

def max_subarray_brute(a):         # the oracle: every non-empty subarray
    return max(sum(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1))

random.seed(7)
for t in range(1, 10_001):
    a = [random.randint(-5, 5) for _ in range(random.randint(1, 8))]   # short arrays, small values
    if max_subarray_buggy(a) != max_subarray_brute(a):
        print(t, a, max_subarray_buggy(a), max_subarray_brute(a))      # 5 [-2, -4] 0 -2
        break

The fifth test fails: on [−2,−4][-2, -4] the buggy code returns 0, the sum of an empty subarray, which the problem does not allow; the answer is −2-2. Every sample with a positive number would have passed.

The first failing input is rarely the simplest one. Before debugging, shrink it: delete pieces while the test still fails. Delta debugging (Zeller & Hildebrandt, 2002) turned this into an algorithm, ddmin, which returns a 1-minimal failing input, one that passes if any single element is removed, using at most quadratically many tests and about log⁡2n\log_2 n when a single element causes the failure. A simplified version fits in a dozen lines:

python
def shrink(a, fails):
    """Delete chunks (halves, quarters, ..., single elements) while the input still fails."""
    chunk = len(a) // 2
    while chunk >= 1:
        i, changed = 0, False
        while i < len(a):
            b = a[:i] + a[i + chunk:]
            if b and fails(b):
                a, changed = b, True       # keep the smaller failing input; retry at the same i
            else:
                i += chunk
        if not changed:
            chunk //= 2
    return a

fails = lambda a: max_subarray_buggy(a) != max_subarray_brute(a)
print(shrink([-3, -1, -4, -1, -5, -9, -2, -6], fails))       # [-6]

Continuing the program above. Eight negative numbers shrink to one, and the bug is now obvious: a single negative number. Every element of the result is necessary, since removing it leaves an empty array, so the result is 1-minimal.

How many tests, and how small?

DerivationProof
  1. Pr⁡[all T tests miss]  =  (1−p)T\Pr[\text{all } T \text{ tests miss}] \;=\; (1 - p)^T

    Independence. Each test misses with probability 1−p1 - p, independently of the others:

  2. (1−p)T  ≤  e−pT  ≤  δ⟸T  ≥  ln⁡(1/δ)p(1 - p)^T \;\le\; e^{-pT} \;\le\; \delta \quad\Longleftarrow\quad T \;\ge\; \frac{\ln(1/\delta)}{p}

    Exponential bound. Since 1−p≤e−p1 - p \le e^{-p} for every real pp (the line lies below the convex curve, touching it at 0):

  3. E[first failing test]  =  ∑t≥1t p (1−p)t−1  =  1p\mathbb{E}[\text{first failing test}] \;=\; \sum_{t \ge 1} t\,p\,(1 - p)^{t-1} \;=\; \frac{1}{p}

    Waiting time. The index of the first failing test is geometric with success probability pp, so its mean is 1/p1/p:

For the Kadane bug, a test fails exactly when every value is negative. The generator draws a length from 1 to 8 uniformly and each value from 11 choices, 5 of them negative, so

p  =  18∑n=18(511)n  ≈  0.104:p \;=\; \frac{1}{8} \sum_{n=1}^{8} \left(\frac{5}{11}\right)^{n} \;\approx\; 0.104:

about 10 tests on average, and 45 tests for 99% certainty. Now draw arrays of length 100 with the same values: p=(5/11)100≈5.7×10−35p = (5/11)^{100} \approx 5.7 \times 10^{-35}, and no amount of testing will ever show the bug.

That is the arithmetic behind the small-scope hypothesis (Jackson): most bugs show up on some small input. It is an empirical observation, not a theorem, but for edge-case bugs the reason is clear: edge cases are common among small inputs and vanishingly rare among large ones.

Predict before you look

Your generator triggers a bug with probability p=0.01p = 0.01 per test. About how many tests make you 99% sure of catching it?

Show the answer

460 tests

ln⁡(100)/0.01≈461\ln(100) / 0.01 \approx 461 by the bound; the exact requirement, 0.99T≤0.010.99^T \le 0.01, gives T≥459T \ge 459. Each extra factor of 10 in confidence costs only ln⁡10/p≈230\ln 10 / p \approx 230 more tests, but a bug ten times rarer costs ten times more: making pp larger with a better generator beats running longer.

For tiny sizes you can drop randomness altogether and test every input: all arrays of length 1 to 6 with values in {−2,…,2}\{-2, \dots, 2\} are only 19,530 cases. Sometimes exhaustive small tests even prove correctness. By the 0–1 principle, a comparator network sorts every input if and only if it sorts all 2n2^n inputs of zeros and ones (the lesson Sorting Networks & Parallel Sorting proves it).

Properties, invariants and nasty inputs

Often there is no slow oracle, or the inputs that matter are too large for one. Property-based testing checks statements that every correct output must satisfy, on generated inputs: QuickCheck (Claessen & Hughes, 2000) introduced it for Haskell, and Hypothesis (MacIver, Hatfield-Dodds et al., 2019) brought it to Python, both with automatic shrinking of failures. Good properties:

  • Postconditions. A sort's output is sorted and has the same multiset of values as its input; the second half catches a "sort" that returns an empty list.
  • Metamorphic relations. Shuffling the input of a maximum-finder changes nothing; reversing an array leaves its maximum subarray sum unchanged; doubling every edge weight doubles every shortest distance.
  • Round trips. Decoding an encoding returns the original; parsing what you printed returns the same value.

Inside the code, invariant assertions check a loop invariant on every pass while testing (binary search's claims about lo and hi, the heap property after each operation), so a bug is caught where it happens rather than where it shows.

Check your understanding

A function counts the distinct values of a sorted array in place: a write index slow starts at 0, each value that differs from a[slow] is copied to a[slow + 1] and slow advances, and the function returns slow + 1. Which input breaks it?

  1. All-equal values, such as [2,2,2][2, 2, 2]
  2. The empty array
  3. A single element, such as [5][5]
  4. No duplicates at all, such as [1,2,3][1, 2, 3]
Show the answer

B. The empty array

On the empty array the loop never runs and the function returns 0+1=10 + 1 = 1, but an empty array has no distinct values. The other inputs give 1, 1 and 3, all correct. "Empty" opens every edge-case checklist for a reason: initializations such as slow = 0 quietly assume that a first element exists.

InputTry
arraysempty; one element; all equal; sorted and reverse sorted; all negative; zeros; the largest nn with the largest values (overflow)
stringsempty; one character; one letter repeated; a pattern equal to the text; overlapping occurrences, such as "aaa" in "aaaaa"
graphsone vertex; no edges; disconnected; self-loops and parallel edges; a long path (deep recursion); a star; a complete graph
numbers0, 1 and −1-1; the limits of the type, such as 231−12^{31} - 1 and −263-2^{63}; primes; powers of two
intervalstouching endpoints, such as [1,3)[1, 3) and [3,5)[3, 5); nested; identical
An edge-case checklist. Random small inputs hit many of these by chance; write the others by hand.

Adversarial inputs aim at worst cases that random inputs miss: sorted arrays for a quicksort that pivots on the first element, keys that all collide under a known hash function (see Hash Flooding & Anti-Hash Tests), and a path of 10610^6 vertices, which overflows the call stack of a recursive depth-first search.

Differential testing runs two independent implementations, for example two compilers, on the same random inputs and flags every disagreement (McKeeman, 1998); a stress test is differential testing with a brute force as the second implementation. Fuzzing feeds random or mutated inputs to a program and watches for crashes: in 1990 Miller, Fredriksen and So crashed or hung a large share of standard UNIX utilities with random input. Coverage-guided fuzzers such as AFL and libFuzzer keep the mutated inputs that reach new code, and Google's OSS-Fuzz service runs them continuously on open-source projects; as of 2025 it reports having helped fix more than 13,000 vulnerabilities and 50,000 bugs across about 1,000 projects.

Checkers and certificates

A test checks an answer you already know. In production, or on inputs too large for any oracle, you want the program to check itself. A program checker (Blum & Kannan, 1989) verifies an output faster than recomputing it; a certifying algorithm (McConnell, Mehlhorn, Näher & Schweitzer, 2011) returns, with its answer, a witness that a simple checker can verify. The classic example checks a matrix product with coin flips.

DerivationProof
  1. (Dr)i  =  dij rj  +  ∑k≠jdik rk⏟y(Dr)_i \;=\; d_{ij}\, r_j \;+\; \underbrace{\textstyle\sum_{k \ne j} d_{ik}\, r_k}_{y}

    Let D=AB−C≠0D = AB - C \ne 0, and pick an entry dij≠0d_{ij} \ne 0. The check passes only if Dr=0Dr = 0, in particular only if row ii gives zero:

  2. Pr⁡[(Dr)i=0  ∣  rk, k≠j]  ≤  12\Pr\big[(Dr)_i = 0 \;\big|\; r_k,\ k \ne j\big] \;\le\; \tfrac12

    The sum yy does not involve rjr_j. Fix all the other coordinates, and with them yy: then (Dr)i=0(Dr)_i = 0 forces rj=−y/dijr_j = -y / d_{ij}, which at most one of the two equally likely values rj∈{0,1}r_j \in \{0, 1\} can satisfy.

  3. Pr⁡[one trial accepts]  ≤  Pr⁡[(Dr)i=0]  ≤  12,Pr⁡[k trials accept]  ≤  2−k\Pr[\text{one trial accepts}] \;\le\; \Pr[(Dr)_i = 0] \;\le\; \tfrac12, \qquad \Pr[k \text{ trials accept}] \;\le\; 2^{-k}

    Averaging over the other coordinates keeps the bound, and independent trials multiply:

python
import random

def matvec(M, v):
    return [sum(m * x for m, x in zip(row, v)) for row in M]

def freivalds(A, B, C, trials=20):
    """False: AB != C for sure. True: AB == C, wrong with probability <= 2**-trials."""
    n = len(C[0])
    for _ in range(trials):
        r = [random.randint(0, 1) for _ in range(n)]
        if matvec(A, matvec(B, r)) != matvec(C, r):   # three O(n^2) products
            return False
    return True

random.seed(1)
n = 60
A = [[random.randint(-9, 9) for _ in range(n)] for _ in range(n)]
B = [[random.randint(-9, 9) for _ in range(n)] for _ in range(n)]
C = [[sum(A[i][t] * B[t][j] for t in range(n)) for j in range(n)] for i in range(n)]
print(freivalds(A, B, C))     # True
C[17][42] += 1                # one wrong entry
print(freivalds(A, B, C))     # False

With one wrong entry, a single trial catches it exactly when r42=1r_{42} = 1: in 20,000 single trials it was caught 50.3% of the time, as the proof predicts for this worst case.

ClaimCertificateCheck
this flow is maximuman ss–tt cut of equal capacityO(n+m)O(n + m): capacities, conservation, the cut's capacity
the graph is bipartitea 2-coloringO(n+m)O(n + m): every edge joins two colors
the graph is not bipartitean odd cycleO(cycle length)O(\text{cycle length})
these are the shortest distances from ssthe distances and a parent for each vertexO(n+m)O(n + m): d[s]=0d[s] = 0, d[v]≤d[u]+w(u,v)d[v] \le d[u] + w(u, v) on every edge, parent edges tight and forming a tree rooted at ss
this array is the sorted inputthe array itselfO(n)O(n) expected: sorted, and equal counts in a hash map
no Hamiltonian cycle existsno short certificate is knownshort certificates for it would imply NP = co-NP, which is believed false
For shortest paths, the triangle inequality summed along a shortest path gives d[v]≤δ(s,v)d[v] \le \delta(s, v), and the tight parent paths give d[v]≥δ(s,v)d[v] \ge \delta(s, v); no labels can satisfy the inequality around a negative cycle, so the check certifies that none exists.

Key takeaways

  • A stress test is an obviously correct oracle, a generator of small random inputs and a comparison loop; shrink the first failure to a minimal input before you debug.
  • If a fraction pp of generated inputs trigger a bug, T≥ln⁡(1/δ)/pT \ge \ln(1/\delta)/p tests catch it with probability 1−δ1 - \delta. Edge cases are frequent among small inputs and vanishingly rare among large ones, so test small.
  • Properties (postconditions, metamorphic relations, round trips), invariant assertions, edge-case checklists and adversarial inputs find bugs without any oracle.
  • Checkers and certificates verify answers faster than recomputing them: Freivalds's test checks a matrix product in O(n2)O(n^2) per trial with error at most 12\tfrac12, a minimum cut certifies a maximum flow, and an odd cycle certifies that a graph is not bipartite.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why is an O(n3)O(n^3) or even exponential brute force acceptable as the oracle in a stress test?

  1. It only ever runs on tiny inputs, and what it must be is obviously correct, not fast
  2. Judges accept slow solutions in testing mode
  3. A slow oracle finds more bugs than a fast one
  4. Random inputs are always small, whatever the generator does
Show the answer

A. It only ever runs on tiny inputs, and what it must be is obviously correct, not fast

The oracle's only job is to be right. On inputs of length 8, even O(2n)O(2^n) is instant, and an oracle simple enough to be checked by eye is what makes a disagreement point at the fast solution.

Question 2

A bug appears only when every element is negative. Your generator draws arrays of length 100 with values from −5-5 to 55. What happens?

  1. It finds the bug within a few hundred tests
  2. It essentially never finds it: the chance per test is about 6×10−356 \times 10^{-35}
  3. It finds it at once, since long arrays exercise more code
  4. It finds it after about 100 tests, one per element
Show the answer

B. It essentially never finds it: the chance per test is about 6×10−356 \times 10^{-35}

All 100 values must be negative: (5/11)100≈5.7×10−35(5/11)^{100} \approx 5.7 \times 10^{-35}. Short arrays trigger it about one test in ten. Generate small inputs.

Question 3

Freivalds's check runs 20 independent trials, each with a fresh random 0/1 vector. If AB≠CAB \ne C, with what probability does it still accept CC?

  1. At most 1/201/20
  2. At most 1/21/2
  3. At most 2−202^{-20}, about 10−610^{-6}
  4. 0
Show the answer

C. At most 2−202^{-20}, about 10−610^{-6}

Each trial independently accepts a wrong product with probability at most 1/21/2, so all 20 do with probability at most 2−20≈9.5×10−72^{-20} \approx 9.5 \times 10^{-7}, for O(20n2)O(20 n^2) work instead of a full multiplication.

Question 4

Which output lets a checker confirm in linear time that a flow is maximum?

  1. The list of augmenting paths the algorithm used
  2. An ss–tt cut whose capacity equals the flow's value
  3. The number of edges in the final residual graph
  4. The running time of the algorithm
Show the answer

B. An ss–tt cut whose capacity equals the flow's value

Every flow is at most every cut's capacity, so a valid flow and a cut of equal value certify each other: both are optimal. Checking capacities, conservation and the cut's capacity takes O(n+m)O(n + m).

Further reading

  • A. Zeller & R. Hildebrandt, "Simplifying and Isolating Failure-Inducing Input," IEEE Transactions on Software Engineering 28(2) (2002).
  • K. Claessen & J. Hughes, "QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs," Proceedings of ICFP (2000).
  • R. Freivalds, "Probabilistic machines can use less running time," Proceedings of the IFIP Congress (1977).
  • M. Blum & S. Kannan, "Designing programs that check their work," Journal of the ACM 42(1) (1995).
  • R. M. McConnell, K. Mehlhorn, S. Näher & P. Schweitzer, "Certifying algorithms," Computer Science Review 5(2) (2011).