Skip to content

Search Insert Position

01 · Question

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

Example:

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

02 · Solution

Reference solution

1def searchInsert(nums: List[int], target: int) -> int:
2 l, r = 0, len(nums) - 1
3
4 while l <= r:
5 mid = (l + r) // 2
6
7 if nums[mid] == target:
8 return mid
9 if nums[mid] < target:
10 l = mid + 1
11 else:
12 r = mid - 1
13
14 return l