Given an array nums of distinct integers sorted in ascending order and an integer target, return the index of target if it is found. If it is not found, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Function Signature
def search_insert(nums: list[int], target: int) -> int:
Rules
-
Indices are 0-based.
-
Because the values in
nums
are distinct,
target
appears at most once, so a found index is unique.
-
When
target
is absent, return the index
i
such that inserting
target
before position
i
keeps the array sorted. The result can be
0
(target smaller than every element) or
len(nums)
(target larger than every element).
Constraints
-
1 <= len(nums) <= 10^4
-
-10^4 <= nums[i] <= 10^4
-
nums
contains distinct values sorted in ascending order.
-
-10^4 <= target <= 10^4
Examples
Input: nums = [1, 3, 5, 6], target = 5
Output: 2
The value 5 is in the array at index 2.
Input: nums = [1, 3, 5, 6], target = 2
Output: 1
The value 2 is not in the array. It belongs between 1 and 3, so inserting it at index 1 keeps the order.
Input: nums = [1, 3, 5, 6], target = 7
Output: 4
The value 7 is larger than every element, so it goes at the end. The insertion index is 4, which equals len(nums).