Overview
Find the first log entry at or after a given time by halving a sorted list at each step, and keep the bounds right so the loop always ends.
- halve the range each step: O(log n)
- keep the answer inside [lo, hi]
- while lo < hi, never an endless loop
Short Course
Binary search halves a sorted range at each step: a million items need only
20 checks. Keep the answer inside [lo, hi] and loop while lo < hi. Trap:
moving a bound to mid instead of past it can loop forever.
def isqrt(n): # largest r, r * r <= n
lo, hi = 0, n
while lo < hi:
mid = (lo + hi + 1) // 2
if mid * mid <= n:
lo = mid
else:
hi = mid - 1
return lo
Task
Write first_at_least(times, t): in the sorted list times, the index of
the first value >= t, or len(times) if there is none. Example:
first_at_least([2, 5, 5, 9], 5) → 1.
Test Suites
Pending
Next
Output