Skip to lesson

Practice: test and fix

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Knowing how to write tests is only half the skill — the real payoff is diagnosing why a piece of code fails on hidden inputs, crafting a minimal test case that proves the bug, and fixing the code without breaking existing cases.

Spotting the five classic bug patterns in DSA code

Most Wrong Answer verdicts come from five recurring mistakes: bad initial value, off-by-one bounds, wrong comparison, int overflow and early return. The code below shows one of them failing.

Example 1 · Exposing and fixing the premature 'else return false' loop bug

PrematureReturnFixDemo.javaJava
public class PrematureReturnFixDemo {    // Buggy: returns false on the very first element if it does not match target!    static boolean buggyContains(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            if (nums[i] == target) {                return true;            } else {                return false;            }        }        return false;    }
    static boolean fixedContains(int[] nums, int target) {        for (int i = 0; i < nums.length; i++) {            if (nums[i] == target) {                return true;            }        }        return false;    }
    public static void main(String[] args) {        int[] input = {10, 20}; // Match is at index 1, not index 0        System.out.println("Sample match at index 0: buggy=" + buggyContains(input, 10)            + ", fixed=" + fixedContains(input, 10));        System.out.println("Exposing match at index 1: buggy=" + buggyContains(input, 20)            + ", fixed=" + fixedContains(input, 20));    }}
Output
Sample match at index 0: buggy=true, fixed=true
Exposing match at index 1: buggy=false, fixed=true

What this code does

  • buggyContains passes when target is at index 0 (10) or when target is absent, which fools a careless tester.
  • A 2-element test where target is at index 1 ([10, 20], target = 20) immediately exposes the premature else return false;.

Most Wrong Answer verdicts in array and string problems come from five recurring mistakes:

  1. Wrong initialisation: Starting max = 0 or min = 0 instead of nums[0] or Integer.MIN_VALUE / Integer.MAX_VALUE (fails on all-negative or all-positive arrays).
  2. Off-by-one loop bounds: Starting at i = 1 instead of 0, or stopping at i < n - 1 instead of i < n (fails when the answer is at the first or last index).
  3. Strict versus inclusive comparison (< vs <=): Using < when ties should be included, or <= when duplicates must be skipped.
  4. 32-bit int overflow: Multiplying or summing values up to 10⁹ inside an int before casting to long.
  5. Premature return inside a loop: Returning true or false on the very first iteration (else return false; inside a search loop) instead of waiting until the loop finishes.
  • Premature else return in a loop only checks index 0 and ignores the rest of the array.
  • max = 0 fails whenever every valid candidate is negative.
  • i < n - 1 misses a match or maximum sitting at the last index.
  • int sum or product overflows silently whenever the true result exceeds 2,147,483,647.

Find the bug

Find the buggy line

Each snippet fails on one small input. Tap the line to blame.

Should return the largest value. It returns 0 for [-4, -2].

Round 1 of 4

How to write a minimal test that exposes a bug

To expose a bug, build the smallest input on which the buggy code and the problem statement disagree. The code below does this for two different bugs.

Example 2 · Exposing and fixing a stateful counter bug in longestConsecutiveOnes

ConsecutiveOnesFixDemo.javaJava
public class ConsecutiveOnesFixDemo {    // Buggy: only updates best inside the 'else' (when a 0 is seen), missing a run at the end!    static int buggyMaxOnes(int[] bits) {        int best = 0, cur = 0;        for (int b : bits) {            if (b == 1) {                cur++;            } else {                best = Math.max(best, cur);                cur = 0;            }        }        return best;    }
    static int fixedMaxOnes(int[] bits) {        int best = 0, cur = 0;        for (int b : bits) {            if (b == 1) {                cur++;                best = Math.max(best, cur);            } else {                cur = 0;            }        }        return best;    }
    static void compare(String label, int[] bits, int expected) {        System.out.println(label            + " | expected=" + expected            + " | buggy=" + buggyMaxOnes(bits)            + " | fixed=" + fixedMaxOnes(bits));    }
    public static void main(String[] args) {        compare("Run in middle [1,1,0,1]", new int[]{1, 1, 0, 1}, 2);        compare("Run at end    [1,0,1,1,1]", new int[]{1, 0, 1, 1, 1}, 3);        compare("All ones      [1,1,1]", new int[]{1, 1, 1}, 3);    }}
Output
Run in middle [1,1,0,1] | expected=2 | buggy=2 | fixed=2
Run at end    [1,0,1,1,1] | expected=3 | buggy=1 | fixed=3
All ones      [1,1,1] | expected=3 | buggy=0 | fixed=3

What this code does

  • Updating best only when a 0 arrives works when the longest streak of 1s is followed by a 0 ([1, 1, 0, 1]).
  • Testing a streak that reaches the end of the array ([1, 0, 1, 1, 1]) or an all-ones array ([1, 1, 1]) exposes the missing update immediately.

Example 3 · Exposing and fixing an integer overflow bug in midpoint / range check

MidpointOverflowFixDemo.javaJava
public class MidpointOverflowFixDemo {    static int buggyMid(int low, int high) {        return (low + high) / 2; // Overflows 32-bit int when low + high > Integer.MAX_VALUE!    }
    static int fixedMid(int low, int high) {        return low + (high - low) / 2;    }
    public static void main(String[] args) {        int low = 1_500_000_000;        int high = 1_700_000_000;        System.out.println("Expected midpoint : 1600000000");        System.out.println("buggyMid          : " + buggyMid(low, high));        System.out.println("fixedMid          : " + fixedMid(low, high));    }}
Output
Expected midpoint : 1600000000
buggyMid          : -547483648
fixedMid          : 1600000000

What this code does

  • (low + high) / 2 works for small array indices, but for low = 1.5 * 10^9 and high = 1.7 * 10^9, low + high = 3.2 * 10^9 overflows 32-bit signed int into a negative number (-547483648).
  • low + (high - low) / 2 (or (low + high) >>> 1 for non-negative ints) stays safely within bounds.

When you suspect a bug in a method, do not write a 20-element test case. Construct the smallest input where the buggy code and the problem specification disagree:

  • If the loop skips index 0 (for (int i = 1; ...)), a 1-element array [target] or a 2-element array [target, 0] exposes it immediately.
  • If the loop has an else return false; on the first non-match, a 2-element array [0, target] where the match is at index 1 exposes it.
  • If an accumulator uses int instead of long, a 2-element array [2_000_000_000, 2_000_000_000] exposes the overflow without needing 100,000 elements.
  1. Read the buggy method and ask: what input shape forces execution down the broken branch?
  2. Build the smallest input (1 to 3 elements) that triggers that branch.
  3. Work out the expected output from the problem statement and assert expected vs actual.
  4. Fix the bug and re-run both the new regression test and all normal/edge tests.

Fixing and re-running: prove the fix without breaking happy paths

A regression is a fix that breaks a case that used to work. The code below shows a hasty loop-bound "fix" that would break every sorted array.

Java
static boolean isSorted(int[] nums) {    for (int i = 0; i < nums.length - 1; i++) { // safe: nums[i + 1] exists        if (nums[i] > nums[i + 1]) return false;    }    return true;}// "Fixed" to i < nums.length, the last pass reads nums[nums.length]:// ArrayIndexOutOfBoundsException on every sorted array, even the happy path

That is why you always re-run the entire test table — normal, boundary, edge, and large cases — after applying a fix. Only when every row prints PASS is the fix complete.

A regression is a fix that breaks a case that used to work. For example, a hasty "fix" for an edge case that changes i < n - 1 to i < n in a loop that accesses nums[i + 1] breaks the normal case too: it throws ArrayIndexOutOfBoundsException!

If a loop reads nums[i + 1], its safe upper bound is i < nums.length - 1; handle the last element separately or adjust what the loop invariant tracks.

Finish up

Mark complete & continue

Next: Array traversal patterns