Easy · Boundary Binary Search
Understand → Visualise → Practice.
Return the first index whose sorted-array value is at least target, or the array length.
Keep a half-open range [lo, hi) that always contains the answer. If nums[mid] < target, the answer is to the right; otherwise mid itself could be it.
hi = n allows the answer 'past the end'.
If nums[mid] < target, lo = mid + 1; else hi = mid.
When lo == hi, it is the first index with nums[i] ≥ target.
O(log n) time and O(1) space.
Using a closed [lo, hi] range with hi = n − 1 can't return n when every value is smaller.
Read the full guides first: Sorting Algorithms and Their Trade-offs, Binary Search and Boundary Finding.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.