Binary Search Lower and upper bounds
228. Floor and Ceil in a Sorted Array
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. For each target, find its floor and its ceiling in nums.
The floor of a target is the largest element of nums that is less than or equal to the target. The
ceiling is the smallest element of nums that is greater than or equal to the target. If no element
qualifies, the answer for that side is -1. Every element is 0 or more, so -1 never looks like a real
element.
Return an array answer with one entry per target, in the order the targets are given:
answer[j] = [floor, ceiling] for targets[j].
Example 1
Input: nums = [3, 3, 8, 12, 12, 12, 20]
targets = [10, 12, 1, 25]
[[8,12],[12,12],[-1,3],[20,-1]]Explanation: 10 lies between 8 and 12. 12 is in nums, so it is its own floor and its own ceiling. Nothing is at most
1, so its floor is −1, and nothing is at least 25, so its ceiling is −1.
Example 2
Input: nums = [6], targets = [6, 0, 9]
[[6,6],[-1,6],[6,-1]]Explanation: With one element, 6 answers every side that exists. 0 has nothing below it and 9 has nothing above it.
Example 3
Input: nums = [0, 0, 1000000000]
targets = [0, 999999999, 1000000000]
[[0,0],[0,1000000000],[1000000000,1000000000]]Explanation: 0 is a real element here, so the floor of 0 is 0, not −1. The smallest and largest allowed values both appear.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 1050 ≤ nums[i] ≤ 109nums[i] ≤ nums[i + 1](non-decreasing)1 ≤ targets.length ≤ 1050 ≤ targets[j] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.