Skip to lesson

The edge case checklist

Passing the sample test in a coding round only means your code works on a friendly, average input. Hidden grading tests deliberately target edge cases—valid inputs pushed to the smallest, largest, or strangest limits of the rules.

Empty input and a single element

An edge case is an input at the limit of what the problem allows, such as an empty array, one element, all equal values, negative numbers or the largest size.

The first two items on the edge-case checklist are size 0 (an empty array [] or empty string "") and size 1 (a single element [x]).

Example 1 · Guard clauses for empty and single-element inputs

GuardClauseDemo.javaJava
public class GuardClauseDemo {    // Problem: Return the largest difference between two adjacent elements    // Math.abs(nums[i] - nums[i - 1]), or 0 if fewer than 2 elements exist.    public static int maxAdjacentGap(int[] nums) {        if (nums == null || nums.length < 2) {            return 0; // Guard clause handles null, [], and [x] in one line        }        int maxGap = 0;        for (int i = 1; i < nums.length; i++) {            int gap = Math.abs(nums[i] - nums[i - 1]);            if (gap > maxGap) {                maxGap = gap;            }        }        return maxGap;    }
    public static void main(String[] args) {        System.out.println("Empty  : " + maxAdjacentGap(new int[]{}));        System.out.println("Single : " + maxAdjacentGap(new int[]{42}));        System.out.println("Normal : " + maxAdjacentGap(new int[]{10, 3, 15, 12}));    }}
Output
Empty  : 0
Single : 0
Normal : 12

What this code does

  • The guard clause if (nums == null || nums.length < 2) return 0; protects the loop so we know nums[0] and nums[1] both exist.
  • With size 0 and size 1 handled upfront, the loop starting at i = 1 is completely safe.

Any code that reads nums[0] or str.charAt(0) before checking the length will crash with an IndexOutOfBoundsException on size 0. Any problem that compares pairs of elements requires at least two items, so size 1 must be handled cleanly.

Checklist: Size 0 ([] or ""): Can the input be empty? If so, write a guard clause (if (nums.length == 0) return ...;) on line 1. Size 1 ([42]): Does a loop starting at i = 1 still return the right initial answer when the loop body never runs? Two-element minimum: If a problem asks for a pair, guard against nums.length < 2 right away.

A guard clause is a short if check at the very top of a method that returns immediately for trivial or empty inputs.

Duplicates, negatives, and zeros

Once size 0 and size 1 are safe, check the values inside the input: duplicates, negatives, and zeros.

Example 2 · The negative odd number trap with Java's % operator

NegativeOddTrapDemo.javaJava
public class NegativeOddTrapDemo {    // Buggy: checks n % 2 == 1, which misses negative odd numbers like -3 and -7!    public static int countOddsBuggy(int[] nums) {        int count = 0;        for (int n : nums) {            if (n % 2 == 1) {                count++;            }        }        return count;    }
    // Fixed: checks n % 2 != 0, which works for both +1 and -1 remainders    public static int countOddsFixed(int[] nums) {        int count = 0;        for (int n : nums) {            if (n % 2 != 0) {                count++;            }        }        return count;    }
    public static void main(String[] args) {        int[] mixed = {-7, -4, -3, 0, 5};        System.out.println("-7 % 2 is     : " + (-7 % 2));        System.out.println("Buggy odd cnt : " + countOddsBuggy(mixed));        System.out.println("Fixed odd cnt : " + countOddsFixed(mixed));    }}
Output
-7 % 2 is     : -1
Buggy odd cnt : 1
Fixed odd cnt : 3

What this code does

  • In Java, the sign of a % b matches the sign of the dividend a, so -7 % 2 evaluates to -1, not 1.
  • Writing n % 2 != 0 handles positive and negative odd numbers identically.

All-duplicate arrays like [5, 5, 5, 5] test whether your < vs <= conditions get stuck or double-count. Negative numbers break max = 0 initializations, flip products when two negatives multiply, and affect the remainder operator (-7 % 2 is -1 in Java, not 1). Zeros cause division-by-zero crashes and turn running products into 0.

Checklist: Duplicates: Test all-equal inputs ([7, 7, 7]) and tied winners ([3, 9, 3, 9]). Negatives: In Java, n % 2 == 1 is false for negative odd numbers like -3 (-3 % 2 == -1); use n % 2 != 0 to test oddness safely. Zeros: Guard against divisor == 0 before / or %, and watch what 0 does to products.

Smallest and largest allowed values

The fourth part of the checklist looks at the smallest and largest numbers allowed by the constraints, especially Integer.MIN_VALUE (-2,147,483,648) and Integer.MAX_VALUE (2,147,483,647).

Example 3 · Extreme value traps: midpoint overflow and Integer.MIN_VALUE

ExtremeValueTrapsDemo.javaJava
public class ExtremeValueTrapsDemo {    public static void main(String[] args) {        int low = 1_500_000_000;        int high = 2_000_000_000;
        int buggyMid = (low + high) / 2; // low + high overflows int!        int safeMid = low + (high - low) / 2;
        System.out.println("Buggy mid : " + buggyMid);        System.out.println("Safe mid  : " + safeMid);
        int minInt = Integer.MIN_VALUE;        System.out.println("Math.abs(int) : " + Math.abs(minInt));        System.out.println("Math.abs(long): " + Math.abs((long) minInt));    }}
Output
Buggy mid : -397483648
Safe mid  : 1750000000
Math.abs(int) : -2147483648
Math.abs(long): 2147483648

What this code does

  • low + high is 3,500,000,000, which wraps around to a negative int before / 2 happens; low + (high - low) / 2 stays within bounds.
  • Casting minInt to long before calling Math.abs avoids the Integer.MIN_VALUE overflow.

In Java 17, 32-bit signed int has one more negative value than positive value. Because +2,147,483,648 cannot fit in an int, Math.abs(Integer.MIN_VALUE) overflows and returns -2,147,483,648 (still negative!). Similarly, computing a midpoint as (low + high) / 2 overflows when low + high > Integer.MAX_VALUE; always write low + (high - low) / 2 instead.

Checklist: Addition / subtraction overflow: Cast to long before adding or subtracting values that can reach 10⁹. Safe midpoint: Use low + (high - low) / 2 instead of (low + high) / 2. Integer.MIN_VALUE trap: Use Math.abs((long) x) if x can be Integer.MIN_VALUE.

Writing edge cases before writing code

Most people try to think of edge cases after they finish coding—when they are already tired and attached to their code. Instead, list your edge cases in Step 4 before you write the method body.

  1. Empty / null: [], ""
  2. Single element: [x], "a"
  3. Duplicates / sorted extremes: [5, 5, 5], already sorted [1, 2, 3], reverse sorted [3, 2, 1]
  4. Negatives and zero: [-10, -3, 0]
  5. Min / max limits: Integer.MAX_VALUE, Integer.MIN_VALUE, maximum length n

Example 4 · Testing all five edge-case categories on a palindrome check

EdgeCaseSuiteDemo.javaJava
public class EdgeCaseSuiteDemo {    // Restatement: Return true if String s reads the same forwards and backwards.    public static boolean isPalindrome(String s) {        if (s == null) {            return false;        }        int left = 0;        int right = s.length() - 1;        while (left < right) {            if (s.charAt(left) != s.charAt(right)) {                return false;            }            left++;            right--;        }        return true;    }
    public static void main(String[] args) {        System.out.println("Empty  (\"\")    : " + isPalindrome(""));        System.out.println("Single (\"a\")   : " + isPalindrome("a"));        System.out.println("All same (\"aaaa\"): " + isPalindrome("aaaa"));        System.out.println("Even len (\"abba\"): " + isPalindrome("abba"));        System.out.println("Mismatch (\"abca\"): " + isPalindrome("abca"));    }}
Output
Empty  ("")    : true
Single ("a")   : true
All same ("aaaa"): true
Even len ("abba"): true
Mismatch ("abca"): false

What this code does

  • On "", left = 0 and right = -1, so left < right is immediately false and the method returns true without ever calling charAt.
  • Testing both odd-length ("a") and even-length ("abba", "abca") strings is a classic string edge case.

Put your edge cases directly into main (or your test list) alongside your normal examples. When you see new int[]{} and new int[]{-5} sitting in main before you start coding, writing the right guard clauses and initial values becomes effortless.

Find the bug

Find the missing edge case

Each method fails on one edge input. Tap the line to fix, then check.

Average of a list of marks. What if the list is empty?

Round 1 of 4

Next step

Check your understanding

10 quick questions