oneby7

Binary Search Lower and upper bounds

228. Floor and Ceil in a Sorted Array

Medium

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]

Output: [[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]

Output: [[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]

Output: [[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.

nums = [2, 4, 4, 7, 9], targets = [4, 8]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109
  • nums[i] ≤ nums[i + 1] (non-decreasing)
  • 1 ≤ targets.length ≤ 105
  • 0 ≤ targets[j] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.