binary-search · Problem 2 of 3

Search Insert Position

medium
Amazon logoAmazon
Adobe logoAdobe

Return the index of target in the sorted array, or the index where it would be inserted to keep it sorted.

searchInsert([1, 3, 5, 6], 5)  ->  2
searchInsert([1, 3, 5, 6], 2)  ->  1

Your solution

Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.

Running is free — Submit is what records it. Or press ⌘↩

Tests

4 cases, 1 hidden
calltypeexpectedresult
searchInsert([1,3,5,6], 5)found2
searchInsert([1,3,5,6], 2)insert middle1
searchInsert([1,3,5,6], 7)insert end4
withheldhiddenwithheld

Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.

Complexity

target time
O(log n)
target space
O(1)

The only change from plain binary search is returning `low` instead of -1 — the position the search converged on.

Hints

Stuck? Hints open one at a time, each giving a little more away.

2 hints left