Search Insert Position

LeetCode: https://leetcode.com/problems/search-insert-position/

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
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
l
1
0
mid
3
1
5
2
r
6
3
target=2
Step 1 / 4
Step 1:
Initialize l=0, r=3. Compute mid=1.
Pointers: l=0, mid=1, r=3
Focus: select @ [1]
target=2