Skip to main content

Search Insert Position

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

Problems33 / 152
Sign in

Search Insert Position

EASYArrayBinary Search

Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

Example 1

Input:  nums = [1,3,5,6], target = 5
Output: 2

Example 2

Input:  nums = [1,3,5,6], target = 2
Output: 1
Show hint

Use binary search. If target found, return index. If not found, return left pointer (it will be at insertion position).

Draft saves automatically

Loading editor...

Submit also runs hidden tests
nums =
[1,3,5,6]
target =
5
Expected
2
Run with your own input (JSON)