Skip to content

Search Insert Position

EasyBinary Search
Decode it first. Clues, constraints, pattern and plan before any code.

You are given a list nums of distinct integers sorted in increasing order and a value target. If target is in nums, return its index. If not, return the index where it would be inserted to keep the list sorted. Your solution should run in O(log n) time.

nums = [2, 4, 7, 9], target = 7    →  2
nums = [2, 4, 7, 9], target = 5    →  2   (between 4 and 7)
nums = [2, 4, 7, 9], target = 10   →  4   (after the end)

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i], target <= 10^4
  • nums is sorted in increasing order with no repeats.