๐ 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 returntrue.
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:
- 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 (
truevsfalse) โ decide the default from the vacuous case. - The negation test. "Every element has length โฅ k" fails exactly
when some element has
length < kโ so theiftests 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 CodeBootcamp drillsImplement contracts, diagnose planted bugs, and widen minimal cases.
5 challenges ยท ยท ~45 min