Binary Search Lower and upper bounds
225. Lower Bound
You are given an array of integers nums, sorted in non-decreasing order, and an array targets. A value can
appear in nums more than once.
The lower bound of a target is the smallest index i with nums[i] >= target. If every element of nums
is smaller than the target, its lower bound is n, the length of nums.
Return an array answer with one entry per target, in the order the targets are given: answer[j] is the
lower bound of targets[j]. Indexes start at 0.
Example 1
Input: nums = [-5, -2, -2, 0, 4, 4, 4, 9]
targets = [4, -2, 1, 10]
[4,1,4,8]Explanation: 4 first appears at index 4, and −2 first appears at index 1. No element equals 1, and the first element larger than it is the 4 at index 4. Every element is smaller than 10, so its answer is n = 8.
Example 2
Input: nums = [6], targets = [6, 2, 11]
[0,0,1]Explanation: 6 and 2 are both at most nums[0], so their answer is 0. 11 is larger than the only element, so its
answer is n = 1.
Example 3
Input: nums = [-1000000000, -1000000000, 0, 1000000000, 1000000000]
targets = [1000000000, -1000000000, -999999999]
[3,0,2]Explanation: Each end of nums holds a run of two equal values, and the answer is where the run starts. −999999999
lies between −109 and 0, so its answer is the index of 0.
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](non-decreasing)1 ≤ targets.length ≤ 105-109 ≤ targets[j] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.