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
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)); }}Sample match at index 0: buggy=true, fixed=true Exposing match at index 1: buggy=false, fixed=true
What this code does
buggyContainspasses whentargetis at index0(10) or whentargetis absent, which fools a careless tester.- A 2-element test where
targetis at index1([10, 20], target = 20) immediately exposes the prematureelse return false;.
Most Wrong Answer verdicts in array and string problems come from five recurring mistakes:
- Wrong initialisation: Starting
max = 0ormin = 0instead ofnums[0]orInteger.MIN_VALUE/Integer.MAX_VALUE(fails on all-negative or all-positive arrays). - Off-by-one loop bounds: Starting at
i = 1instead of0, or stopping ati < n - 1instead ofi < n(fails when the answer is at the first or last index). - Strict versus inclusive comparison (
<vs<=): Using<when ties should be included, or<=when duplicates must be skipped. - 32-bit
intoverflow: Multiplying or summing values up to 10⁹ inside anintbefore casting tolong. - Premature
returninside a loop: Returningtrueorfalseon the very first iteration (else return false;inside a search loop) instead of waiting until the loop finishes.
- Premature
else returnin a loop only checks index0and ignores the rest of the array. max = 0fails whenever every valid candidate is negative.i < n - 1misses a match or maximum sitting at the last index.intsum 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 4How 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
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); }}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
bestonly when a0arrives works when the longest streak of1s is followed by a0([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
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)); }}Expected midpoint : 1600000000 buggyMid : -547483648 fixedMid : 1600000000
What this code does
(low + high) / 2works for small array indices, but forlow = 1.5 * 10^9andhigh = 1.7 * 10^9,low + high = 3.2 * 10^9overflows 32-bit signedintinto a negative number (-547483648).low + (high - low) / 2(or(low + high) >>> 1for non-negativeints) 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 index1exposes it. - If an accumulator uses
intinstead oflong, a 2-element array[2_000_000_000, 2_000_000_000]exposes the overflow without needing 100,000 elements.
- Read the buggy method and ask: what input shape forces execution down the broken branch?
- Build the smallest input (1 to 3 elements) that triggers that branch.
- Work out the expected output from the problem statement and assert
expectedvsactual. - 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.
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 pathThat 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!
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