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 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 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.
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
breakThe fifth test fails: on the buggy code returns 0, the sum of an empty subarray, which the problem does not allow; the answer is . 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 when a single element causes the failure. A simplified version fits in a dozen lines:
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?
Independence. Each test misses with probability , independently of the others:
Exponential bound. Since for every real (the line lies below the convex curve, touching it at 0):
Waiting time. The index of the first failing test is geometric with success probability , so its mean is :
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
about 10 tests on average, and 45 tests for 99% certainty. Now draw arrays of length 100 with the same values: , 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.
Your generator triggers a bug with probability per test. About how many tests make you 99% sure of catching it?
Show the answer
460 tests
by the bound; the exact requirement, , gives . Each extra factor of 10 in confidence costs only more tests, but a bug ten times rarer costs ten times more: making 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 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 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.
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?
- All-equal values, such as
- The empty array
- A single element, such as
- No duplicates at all, such as
Show the answer
B. The empty array
On the empty array the loop never runs and the function returns , 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.
| Input | Try |
|---|---|
| arrays | empty; one element; all equal; sorted and reverse sorted; all negative; zeros; the largest with the largest values (overflow) |
| strings | empty; one character; one letter repeated; a pattern equal to the text; overlapping occurrences, such as "aaa" in "aaaaa" |
| graphs | one vertex; no edges; disconnected; self-loops and parallel edges; a long path (deep recursion); a star; a complete graph |
| numbers | 0, 1 and ; the limits of the type, such as and ; primes; powers of two |
| intervals | touching endpoints, such as and ; nested; identical |
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 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.
Let , and pick an entry . The check passes only if , in particular only if row gives zero:
The sum does not involve . Fix all the other coordinates, and with them : then forces , which at most one of the two equally likely values can satisfy.
Averaging over the other coordinates keeps the bound, and independent trials multiply:
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)) # FalseWith one wrong entry, a single trial catches it exactly when : in 20,000 single trials it was caught 50.3% of the time, as the proof predicts for this worst case.
| Claim | Certificate | Check |
|---|---|---|
| this flow is maximum | an – cut of equal capacity | : capacities, conservation, the cut's capacity |
| the graph is bipartite | a 2-coloring | : every edge joins two colors |
| the graph is not bipartite | an odd cycle | |
| these are the shortest distances from | the distances and a parent for each vertex | : , on every edge, parent edges tight and forming a tree rooted at |
| this array is the sorted input | the array itself | expected: sorted, and equal counts in a hash map |
| no Hamiltonian cycle exists | no short certificate is known | short certificates for it would imply NP = co-NP, which is believed false |
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 of generated inputs trigger a bug, tests catch it with probability . 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 per trial with error at most , 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.
Why is an or even exponential brute force acceptable as the oracle in a stress test?
- It only ever runs on tiny inputs, and what it must be is obviously correct, not fast
- Judges accept slow solutions in testing mode
- A slow oracle finds more bugs than a fast one
- 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 is instant, and an oracle simple enough to be checked by eye is what makes a disagreement point at the fast solution.
A bug appears only when every element is negative. Your generator draws arrays of length 100 with values from to . What happens?
- It finds the bug within a few hundred tests
- It essentially never finds it: the chance per test is about
- It finds it at once, since long arrays exercise more code
- 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
All 100 values must be negative: . Short arrays trigger it about one test in ten. Generate small inputs.
Freivalds's check runs 20 independent trials, each with a fresh random 0/1 vector. If , with what probability does it still accept ?
- At most
- At most
- At most , about
- 0
Show the answer
C. At most , about
Each trial independently accepts a wrong product with probability at most , so all 20 do with probability at most , for work instead of a full multiplication.
Which output lets a checker confirm in linear time that a flow is maximum?
- The list of augmenting paths the algorithm used
- An – cut whose capacity equals the flow's value
- The number of edges in the final residual graph
- The running time of the algorithm
Show the answer
B. An – 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 .
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).