Algorithms and Data Structures · Middle · Question 13 of 75

What does this binary search return when target is not in the array?

function lowerBound(arr, target) {
  let lo = 0, hi = arr.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (arr[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  return lo;
}

Explanation

This is lower bound: the first index whose value is >= target. If all values are smaller it returns arr.length. It's the basis of many variations: counting occurrences, finding ranges, inserting into a sorted array.

Further reading

Problem with a question

Algorithms and Data Structures · Middle · question 13

Test yourself

Take the Algorithms and Data Structures · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz