Search Insert Position

Easy#35find a number

You get a sorted array of distinct numbers and a target. Return the index of the target if it is there; if not, the index where it would go so the array stays sorted. It has to take O(log n) time. Our example: [1, 4, 6, 9, 13, 17] and 10 — the answer is 4: 10 goes between 9 and 13.

input
nums: different integers in ascending order; target: an integer.
returns
The index of target in nums, or the index where it would be inserted to keep the order. LeetCode wants it in O(log n).
constraints
  • 1 ≤ nums.length ≤ 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • nums is in ascending order, all different
  • −10⁴ ≤ target ≤ 10⁴
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
function searchInsert(nums, target) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more binary search problems

Pattern “Binary search” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.