Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Recursion

    The Classic Bugs

    A debugging technique that always works: print the arguments on entry and the return value on exit, with indentation by depth — exactly the trace in Chapter 2.

    Chapter 9 of 92 min read

    BugExampleSymptomFix
    no base casef(n) { return f(n - 1); }StackOverflowErroralways write the base case first
    no progressf(n) { ... return f(n); } or f(n + 1) heading away from the baseStackOverflowErrorcheck every call moves toward the base case
    base case misses inputsbase n == 0, but called with negative nStackOverflowError on some inputsuse n <= 0 / handle all "smallest" cases
    ignoring the return valuecountNotes(sub); without total +=answer too smalluse every recursive result
    forgetting to unchoosebacktracking without undowrong/duplicated resultsundo every change after exploring (Ch 6)
    sharing a mutable result by accidentout.add(chosen) storing the same StringBuilder/listevery result looks identical at the endstore a copy: out.add(chosen.toString()) / new ArrayList<>(path)
    hidden copyingsubstring, copyOfRange at every levelO(n²) instead of O(n)recurse on indexes
    exponential blow-upoverlapping subproblems unmemoizedTLE on moderate nmemoize (Ch 7)
    too deeplinear recursion on 10⁵+ elementsStackOverflowErrorexplicit stack / loop (Ch 8)

    A debugging technique that always works: print the arguments on entry and the return value on exit, with indentation by depth — exactly the trace in Chapter 2. Run it on the smallest input that fails.