Binary Search

Easy
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Binary Search

Approach

Maintain two pointers enclosing the search space. Compute the midpoint and compare its value to the target. If equal, return. If less, discard the left half. If greater, discard the right half. Repeat until the pointers cross.

Complexity Analysis

Time
O(log n)
Space
O(1)

Pattern

Binary Search (Classic)

Why It Works

Array is sorted, so comparing the midpoint tells us which half contains the target, eliminating half the search space each iteration.

Updated Feb 2026