Bitpath

Lesson 2 · Unit 01

Getting the bounds right

Off-by-one bugs and how to avoid them

12 exercisesabout 3 min

What you practise

  • lo <= hi, mid ± 1, the infinite-loop bug, integer division per language

Try a question from this lesson

Pick one

This search has a one-character bug: the loop says lo < hi. What does it print?

def search(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print(search([1, 3, 5, 7], 7))
function search(nums, target) {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (nums[mid] === target) return mid;
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}

console.log(search([1, 3, 5, 7], 7));
function search(
  nums: number[],
  target: number,
): number {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (nums[mid] === target) return mid;
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid - 1;
  }
  return -1;
}

console.log(search([1, 3, 5, 7], 7));

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

The window is inclusive

In this style of binary search, lo and hi are both indexes the target could still be at.

So three choices must agree: hi starts at the last index, the loop runs while lo <= hi (the window is empty only when lo passes hi), and a checked mid is excluded with mid + 1 or mid - 1.

Mix conventions and you get a skipped item or an endless loop.

Concept

Halving an index

The middle of lo..hi is their average, rounded down to a whole index.

Python has integer division built in: //. JavaScript and TypeScript have one number type, so / can produce 3.5: round it with Math.floor.

With two items left, rounding down picks the left one, lo itself. Remember that when a search stalls.

lo, hi = 0, 7
print((lo + hi) // 2)   # 3
print((lo + hi) / 2)    # 3.5
const lo = 0, hi = 7;
const sum = lo + hi;
console.log(Math.floor(sum / 2)); // 3
console.log(sum / 2);             // 3.5
const lo = 0, hi = 7;
const sum = lo + hi;
console.log(Math.floor(sum / 2)); // 3
console.log(sum / 2);             // 3.5

Python notePython integers never overflow, so (lo + hi) // 2 is safe for any size of list.

TypeScript noteTypeScript has no separate integer type: mid is a number whether or not you floor it. The compiler will not catch a fractional index.

9 more exercises in the app

  • 2× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 1× true or false
  • 1× match the pairs

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy