Skip to content

visual walkthrough

Search Insert Position

EasyLower / Upper BoundReported at: AmazonAppleGoogle+6

Lower bound: the first index whose value is ≥ target.

Solve on LeetCode

The idea

The answer is the first position whose value is at least the target: where it is, or where it would be inserted.

Binary search for that boundary: keep a range that always contains it, and halve it.

Complexity

approachtimespace
Scan from the leftO(n)O(1)
Binary search (lower bound)O(log n)O(1)

More walkthroughs