What is Binary Search
The array is sorted. Return the first index of target, or -1 when it is missing. Each step checks the middle and throws away the half that cannot contain that first index. A linear scan is too slow on the large test.
6 9 -1 0 3 5 9 12 4
Approach
The array is sorted, so each guess throws away half of the remaining indexes. The search remembers the leftmost match, because the problem asks for the first index of the target.
The window shrinks until lo passes hi. If no match was saved, the answer is -1.
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(log n) | The range halves on every comparison. |
| Memory | O(1) | Only the two ends and the stored index are kept. |
Implementation
def first_index(a, target):
lo, hi, ans = 0, len(a) - 1, -1
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] >= target:
if a[mid] == target:
ans = mid
hi = mid - 1
else:
lo = mid + 1
return ans