Bitpath

Boss lesson · Unit 01

First position ≥ target

The lower bound: insertion points and counting duplicates

13 exercisesabout 3 min

What you practise

  • The lower-bound template
  • Insertion point
  • Counting occurrences with two bounds

Try a question from this lesson

Pick one

The list has three 3s, at indexes 1, 2 and 3. Which index does this plain binary search 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, 3, 3, 5], 3))
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, 3, 3, 5], 3));
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, 3, 3, 5], 3));

The idea

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

Concept

The lower bound

The lower bound of a target is the first index whose value is at least the target.

The window is half-open: hi starts at the length, one past the end. A middle value that is too small cannot be the answer: lo = mid + 1. Anything else might be the answer, so keep it: hi = mid. When lo meets hi, that index is the answer.

def lower_bound(nums, target):
    lo, hi = 0, len(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo
function lowerBound(nums, target) {
  let lo = 0, hi = nums.length;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}
function lowerBound(
  nums: number[],
  target: number,
): number {
  let lo = 0, hi = nums.length;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

Python noteThe standard library has this built in: bisect.bisect_left(nums, target).

TypeScript noteJavaScript and TypeScript have no built-in binary search, so this function is worth knowing by heart.

11 more exercises in the app

  • 3× type the answer
  • 4× 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