Find First and Last Position

Med
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: Find First and Last Position

Approach

Run binary search twice. The first search is left-biased: when it finds the target, it records the index and keeps searching left. The second is right-biased and keeps searching right. Together they find both boundaries.

Complexity Analysis

Time
O(log n)
Space
O(1)

Pattern

Binary Search (Boundary Finding)

Why It Works

Running binary search twice with different bias — left-biased continues searching left even after finding a match to find the first occurrence, right-biased does the opposite.

Updated Feb 2026