Skip to lesson

Stress testing against brute force

Sometimes your fast O(n) solution fails a hidden judge test, yet every hand-made test case you can think of passes. Stress testing (also called differential testing) lets the computer invent thousands of small random inputs and compare your fast code against a dead-simple brute-force method until they disagree.

The two-solution trick: slow-but-obvious versus fast-but-tricky

Stress testing is running a fast solution and a simple brute-force solution on many random inputs and comparing their answers to find hidden bugs.

Stress testing compares a slow, obviously correct solution with your fast one on many small inputs. The code below catches a duplicate-value bug in secondLargest this way.

A stress test runs a loop of 1,000 to 10,000 trials. In each trial, it generates a small random input (for example, length 1 to 8 with values -5 to 5), runs both slowSolve and fastSolve on that input, and stops the instant their answers differ.

The buggy fast version on [5, 5, 3]

Step 1 of 4

Array: 5, 5, 3.
first
-1
second
-1
The slow reference says the second largest distinct value of [5, 5, 3] is 3. Now we trace the buggy fast version.

Example 1 · Stress testing catches a subtle duplicate-element bug in secondLargest

StressTestDemo.javaJava
import java.util.Arrays;import java.util.Random;
public class StressTestDemo {    // Slow but obviously correct O(n log n) reference    static int slowSecondLargestDistinct(int[] nums) {        int[] copy = nums.clone();        Arrays.sort(copy);        int largest = copy[copy.length - 1];        for (int i = copy.length - 2; i >= 0; i--) {            if (copy[i] < largest) {                return copy[i];            }        }        return -1; // All elements equal    }
    // Fast O(n) attempt with a subtle bug when x == first    static int buggyFastSecondLargestDistinct(int[] nums) {        int first = -1;        int second = -1;        for (int x : nums) {            if (x > first) {                second = first;                first = x;            } else if (x > second) { // Bug: forgot 'x < first'                second = x;            }        }        return second;    }
    public static void main(String[] args) {        Random rng = new Random(42L);        int mismatches = 0;        for (int t = 0; t < 200; t++) {            int[] arr = new int[4];            for (int i = 0; i < arr.length; i++) {                arr[i] = 1 + rng.nextInt(5); // values in [1..5] encourage duplicates            }            int expected = slowSecondLargestDistinct(arr.clone());            int actual = buggyFastSecondLargestDistinct(arr.clone());            if (expected != actual) {                mismatches++;            }        }        System.out.println("Found mismatch: " + (mismatches > 0));        // Verify the exact duplicate pattern that triggers the bug:        int[] witness = {5, 5, 3};        System.out.println("Witness [5, 5, 3] -> slow="            + slowSecondLargestDistinct(witness)            + ", buggyFast=" + buggyFastSecondLargestDistinct(witness));    }}
Output
Found mismatch: true
Witness [5, 5, 3] -> slow=3, buggyFast=5

What this code does

  • By keeping the random value range narrow (1..5), the stress test frequently generates duplicate maximums like [5, 5, 3].
  • When the second 5 arrives, buggyFastSecondLargestDistinct takes the else if (x > second) branch and overwrites second with 5 because it forgot to check x < first.

For almost every DSA problem, there are two ways to solve it:

  1. A brute-force reference (slowSolve) that checks every possibility with nested loops. It is too slow for n = 100,000, but for n <= 10 it finishes in microseconds and is so simple that it is almost impossible to get wrong.
  2. Your optimised solution (fastSolve) that uses two pointers, a hash map, or greedy logic. It runs in O(n) time, but has subtle boundary conditions where a bug can hide.
  • slowSolve: easy to trust, slow on huge inputs, fast on tiny inputs (n <= 10).
  • fastSolve: fast on huge inputs, harder to get right on every edge case.
  • Small random inputs (n <= 8, narrow value range) hit ties, zeroes, and negatives far more often than huge arrays with wide random ranges.

Generating repeatable random inputs with java.util.Random

In Java, java.util.Random generates pseudo-random numbers. If you call new Random() with no arguments, Java picks a seed based on the system clock, so every run produces different inputs. That is frustrating when a bug appears on one run and vanishes on the next.

Example 2 · A fixed seed in java.util.Random guarantees identical test inputs on every run

SeededRandomDemo.javaJava
import java.util.Arrays;import java.util.Random;
public class SeededRandomDemo {    static int[] randomArray(Random rng, int length, int minVal, int maxVal) {        int[] arr = new int[length];        int span = maxVal - minVal + 1;        for (int i = 0; i < length; i++) {            arr[i] = minVal + rng.nextInt(span);        }        return arr;    }
    public static void main(String[] args) {        Random runA = new Random(42L);        Random runB = new Random(42L);
        boolean allMatched = true;        for (int trial = 1; trial <= 5; trial++) {            int[] a = randomArray(runA, 4, -5, 5);            int[] b = randomArray(runB, 4, -5, 5);            if (!Arrays.equals(a, b)) {                allMatched = false;            }        }        System.out.println("Two Random(42L) streams identical across 5 arrays: " + allMatched);    }}
Output
Two Random(42L) streams identical across 5 arrays: true

What this code does

  • new Random(42L) starts from a fixed mathematical seed, so runA and runB generate the exact same sequence of arrays.
  • Using a fixed seed means that when trial #37 fails, you can add a breakpoint on trial == 37 and replay the exact same failure.
  1. Create Random rng = new Random(42L); with a fixed seed so every run is repeatable.
  2. Pick a small random length: int n = 1 + rng.nextInt(maxLen);.
  3. Fill int[] arr = new int[n] using minVal + rng.nextInt(maxVal - minVal + 1).
  4. Pass arr.clone() to both slowSolve and fastSolve so neither method mutates the other's input.

Instead, pass a fixed seed such as new Random(42L). A seed is the starting number for the random generator's formula. With the same seed, Random produces the exact same sequence of numbers every time you run the program, making any failure 100% repeatable while you debug. To generate an integer in a custom inclusive range [min, max], use min + rng.nextInt(max - min + 1). For example, -5 + rng.nextInt(11) produces a random integer from -5 to +5 inclusive.

Shrinking a failing case to the smallest counterexample

Tracing a failing array of 12 elements like [3, -4, 2, -5, 0, 1, -2, 4, -3, 2, -1, 5] by hand is still tedious. Once your stress test finds an input where fastSolve(arr) != slowSolve(arr), you can shrink (or minimise) the failing input automatically.

Example 3 · Automatically shrinking a failing random case down to a minimal counterexample

ShrinkCounterexampleDemo.javaJava
import java.util.Arrays;import java.util.Random;
public class ShrinkCounterexampleDemo {    // Correct reference: maximum subarray sum (at least 1 element)    static int bruteMaxSubarray(int[] a) {        int best = Integer.MIN_VALUE;        for (int i = 0; i < a.length; i++) {            int sum = 0;            for (int j = i; j < a.length; j++) {                sum += a[j];                best = Math.max(best, sum);            }        }        return best;    }
    // Buggy fast solution: initialises best to 0 (fails when all numbers are negative)    static int buggyKadane(int[] a) {        int best = 0;        int cur = 0;        for (int x : a) {            cur = Math.max(0, cur + x);            best = Math.max(best, cur);        }        return best;    }
    static boolean fails(int[] a) {        return bruteMaxSubarray(a) != buggyKadane(a);    }
    static int[] shrink(int[] failing) {        int[] current = failing.clone();        // Step 1: shrink to the shortest prefix or single element that still fails        for (int x : current) {            int[] single = {x};            if (fails(single)) {                current = single;                break;            }        }        // Step 2: shrink the value magnitude toward 0        for (int i = 0; i < current.length; i++) {            if (current[i] < 0) {                for (int v = -1; v > current[i]; v--) {                    int old = current[i];                    current[i] = v;                    if (fails(current)) break;                    current[i] = old;                }            }        }        return current;    }
    public static void main(String[] args) {        Random rng = new Random(42L);        int[] found = null;        for (int t = 0; t < 500; t++) {            int[] candidate = new int[4];            for (int i = 0; i < 4; i++) {                candidate[i] = -5 + rng.nextInt(10); // [-5 .. 4]            }            if (fails(candidate)) {                found = candidate;                break;            }        }        int[] minimal = shrink(found);        System.out.println("Shrunk counterexample: " + Arrays.toString(minimal));        System.out.println("Expected: " + bruteMaxSubarray(minimal)            + ", Actual: " + buggyKadane(minimal));    }}
Output
Shrunk counterexample: [-1]
Expected: -1, Actual: 0

What this code does

  • The seeded random loop quickly hits a 4-element all-negative array where bruteMaxSubarray and buggyKadane disagree.
  • The shrink helper reduces the 4-element random array to a 1-element array and pulls its value toward zero, producing the cleanest possible counterexample: [-1].

Shrinking works in two quick passes:

  1. Shrink length: try shorter prefixes or single-element slices of the failing array, keeping the first smaller array that still causes fastSolve and slowSolve to disagree.
  2. Shrink values: move each element closer to 0 (for example, replacing -5 with -1) as long as the mismatch remains. Often a 10-element random failure shrinks down to a 1- or 2-element array like [-1] or [2, 2], which makes the bug obvious at a single glance.
Always pass arr.clone() when calling slowSolve and fastSolve in a stress test so an in-place modification in one method does not corrupt the input for the other.

Next step

Check your understanding

10 quick questions