awelgorithms

Lower bound is the first index not less

Updated

Lower bound is the first index i with a[i] >= target, or n if every value is smaller. It is a boundary, not an equality test. Equals stay in the range: if a[mid] < target then L = mid+1 else R = mid.

What to focus on

Start L=0, R=n. Loop while L < R. Return L. Lower bound of 4 in [1, 4, 4, 9] is index 1.

Worked examples

first >= 4

a = [1, 4, 4, 9], target 4
  1. L=0 R=4 mid=2 a[2]=4 not < 4 so R=2
  2. L=0 R=2 mid=1 a[1]=4 not < 4 so R=1
  3. L=0 R=1 mid=0 a[0]=1<4 so L=1
  4. L=1 R=1

Result: lower bound 1

first >= 1

a = [1, 4, 9], target 1
  1. L=0 R=3 mid=1 a[1]=4 not < 1 so R=1
  2. L=0 R=1 mid=0 a[0]=1 not < 1 so R=0
  3. L=0 R=0

Result: lower bound 0

one cell

a = [7], target 7
  1. L=0 R=1 mid=0 a[0]=7 not < 7 so R=0
  2. L=0 R=0

Result: lower bound 0

Try it

Write lowerBound(a, t). a is a sorted array. t is the target. L, mid, and R are indices. R starts at n. If a[mid] >= t then R = mid, else L = mid+1. Return the first index i with a[i] >= t, or n. [1, 4, 4, 9] t=4 must return 1. [1, 4, 4, 9] t=4 → 1 [1, 4, 9] t=1 → 0 [7] t=7 → 0

a is sorted non-decreasing and non-empty. t is an integer. L, mid, and R are indices.