binary-search · Problem 2 of 3
Search Insert Position
medium
Amazon
Adobe
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) -> 1Your 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| call | type | expected | result |
|---|---|---|---|
| searchInsert([1,3,5,6], 5) | found | 2 | — |
| searchInsert([1,3,5,6], 2) | insert middle | 1 | — |
| searchInsert([1,3,5,6], 7) | insert end | 4 | — |
| withheld | hidden | withheld | — |
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