awelgorithms

Range of a value is lower to upper

Updated

The copies of target occupy [lowerBound(target), upperBound(target)). Count is upper - lower. If the target is missing, lower == upper and the half-open range is empty.

What to focus on

Run both bound searches. For 4 in [1, 4, 4, 9] the range is [1, 3) — indices 1 and 2.

Worked examples

two copies

a = [1, 4, 4, 9], target 4
  1. lower=1
  2. upper=3
  3. indices 1,2

Result: [1, 3) count 2

one copy

a = [1, 4, 9], target 4
  1. lower: L=0 R=3 mid=1 a[1]=4, shrinks to L=1
  2. upper: L=0 R=3 mid=1 a[1]=4 <=4 so L=2, then R=2

Result: [1, 2) count 1

empty range

a = [1, 4, 4, 9], target 5
  1. lower=3 first >= 5
  2. upper=3 first > 5
  3. no index in between

Result: [3, 3) count 0

Try it

Write equalRange(a, t). a is a sorted array. t is the target. L, mid, and R are indices on each bound search. The range is [lower, upper). Return both bounds. [1, 4, 4, 9] t=4 → [1, 3) t=5 → [3, 3) [1, 4, 9] t=4 → [1, 2)

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