CONCEPT · Novice

Off-by-one

also OBOE · inclusive exclusive

The most common WA: iterating one index too far, dropping the last element of a reverse, or mixing 0-based code with 1-based statements.

Intuition

Name the range. Write 'i from l to r inclusive' or 'half-open [l, r)' and do not switch conventions inside one function.

When to reach for it

  • Every loop you write
  • Binary search boundaries
  • Prefix index identities

Usual pits

  • a[i+1] on the last index
  • pref[r] - pref[l] when you meant pref[l-1]
  • hi = mid - 1 vs hi = mid depending on the invariant
Open the lesson