Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Module 02 · DSA · Choosing the attack · about 24 min to read

Play it as a journeyTutor comes with a plan

Why the loop is right

Sorting and Searching
Sorting and Searching · Open board

Is the board this lesson reads closely. Its binary search panel marks lo, mid and hi over the sorted list 1 to 15, and one line underneath warns about the off-by-one: “nail the invariant (is hi inclusive? is the answer in [lo,hi]?) or you loop forever / skip it.” This lesson is that one line, taken seriously.

Before you start. Sorting & Searching gave you binary search: on a sorted list, look at the middle, throw away the half that cannot hold what you want, repeat, so a million items takes about twenty looks. Recursion & Dynamic Programming gave you recursion: a function that calls itself on a smaller copy of the problem, stopped by a base case it can answer directly.

Lesson 12 of 96 in DSA

The rest of this lesson is part of a plan.

A plan opens every lesson, board, video, lab and paper on chalk. Yearly is $39/year.

See plansAlready a member? Sign in

Or start free: a free account opens lessons 2 and 3 of every track.

In this lesson

  • 1983: a hundred professional programmers, one binary search, ninety percent wrong
  • The off-by-one: four bugs, each one character from right
  • The promise the range keeps: a loop invariant
  • Four questions that catch every off-by-one
  • Recursion: the same promise, handed to a smaller call, is induction
  • Greedy: a promise that the choices so far can still win, kept by the exchange argument
  • The four bugs, counted
  • Each bug, watched breaking its question
  • The promise, asserted on every lap
  • Induction, run
  • The same habit on the other templates
  • In an interview

Terms it explains: off-by-one, loop invariant, induction, exchange argument, Half-open, Lower bound, Test the boundaries, binary search, Search Insert Position, First Bad Version, Non-overlapping Intervals, binary-search-on-the-answer, comparison sort, counting/radix/bucket, external sort, heapsort, in-place, invariant, merge sort, pivot/partition, quicksort, stable sort, the O(n log n) wall, Timsort/introsort.

Review DSA