Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Solve small, then widen

โญโญ intermediateโณ 10 min read๐Ÿ“ Lesson 82 of 256

The early-exit pattern, the negation test, and widening minimal cases.

The AP style guide for humans: solve the smallest version of the problem first, then widen it.

Take: "Return true if every element of words has length at least k."

  • Smallest case: an empty array. "Every element" of nothing is vacuously true โ€” return true.
  • One element: check words[0].length() >= k.
  • All elements: loop, and the moment one fails, return false. Only after the loop finishes may you return true.
public static boolean allLong(String[] words, int k) {
    for (String w : words) {
        if (w.length() < k) {
            return false;
        }
    }
    return true;
}

Two habits this procedure builds:

  1. The early-exit pattern. "Every / no / none" questions want you to return the moment the answer is decided, then give the default after the loop. Students who instead try to track a flag often initialize it wrong (true vs false) โ€” decide the default from the vacuous case.
  2. The negation test. "Every element has length โ‰ฅ k" fails exactly when some element has length < k โ€” so the if tests the failure, not the success. Translating negations correctly is worth points on nearly every exam.

The same widening works for accumulation (sum โ†’ sum with condition โ†’ count of condition) and for searching (does it exist โ†’ where โ†’ first occurrence). Start where the problem is already solved; add complexity one obligation at a time.

โšก Now practice

Ready to Code
Bootcamp drillsImplement contracts, diagnose planted bugs, and widen minimal cases.
5 challenges ยท ยท ~45 min