Divide & Conquer · Search

Binary Search Visualizer

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.

Too smallIf the middle value is below the target, every index at or left of the middle is too small. Move lo to mid + 1.
Too big or equalIf the middle value is above the target, or it matches, the first copy can only be at mid or to the left. Save mid when it matches, then set hi to mid - 1.

The window shrinks until lo passes hi. If no match was saved, the answer is -1.

Interactive solution

lo, mid, and hi on a sorted row
lo, hi = 0, n - 1
ans = -1
while lo <= hi:
if a[mid] == target: ans = mid; hi = mid - 1
elif a[mid] > target: hi = mid - 1
else: lo = mid + 1
return ans
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(log n)The range halves on every comparison.
MemoryO(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