oneby7

Binary Search Lower and upper bounds

226. Upper Bound

Medium

You are given an array of integers nums, sorted in non-decreasing order, and an array targets. Non-decreasing means each element is at least as large as the one before it, so a value can repeat.

The upper bound of a target is the smallest index i with nums[i] > target. If no element is greater than the target, the upper 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 upper bound of targets[j]. Indexes start at 0. A target does not have to appear in nums.

Example 1

Input: nums = [1, 3, 3, 3, 6, 8, 8, 11] targets = [3, 8, 5, 11, 0]

Output: [4,7,4,8,0]

Explanation: The three 3s sit at indexes 1 to 3, so the first larger value is the 6 at index 4. For 8 it is the 11 at index 7. 5 is missing, and 6 at index 4 is still the first larger value. Nothing is larger than 11, so its answer is 8, the length. Every element is larger than 0, so its answer is 0.

Example 2

Input: nums = [4, 4, 4, 4], targets = [4, 3, 5]

Output: [4,0,4]

Explanation: No element is larger than 4 or 5, so both answers are the length, 4. Every element is larger than 3.

Example 3

Input: nums = [-1000000000, -5, -5, 0, 1000000000] targets = [-5, 1000000000, -1000000000, -6]

Output: [3,5,1,1]

Explanation: The first value above −5 is the 0 at index 3. Nothing is above 109, so its answer is 5. The first value above −109 and above −6 is the −5 at index 1.

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 5, 5, 5, 9], targets = [5]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums[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.

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.