Binary Search Lower and upper bounds
227. Search Insert Position
You are given an array of distinct integers nums, sorted in increasing order, and an integer target. If
target is in nums, return its index. If it is not, return the index it would have if it were inserted into
nums with the order kept.
Indexes start at 0. You only return the index; nums itself does not change. Aim for a running time of
O(log n).
Example 1
Input: nums = [-6, -2, 3, 8, 14, 20], target = 9
4Explanation: 9 is not in nums. It belongs after 8 and before 14, so once inserted it would sit at index 4, where 14
is now.
Example 2
Input: nums = [2, 5, 9], target = 40
3Explanation: 40 is larger than every element, so it would go after the last one. That is index 3, one past the end of
nums.
Example 3
Input: nums = [-1000000000, -50, 0, 50], target = -50
1Explanation: −50 is already in nums, at index 1, so the answer is that index.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109nums[i] < nums[i + 1](strictly increasing, so all values are distinct)-109 ≤ target ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.