![]() |
VOOZH | about |
Given a sorted array arr[] and a number target, find the upper bound of the target in this given array. The upper bound of a number is defined as the smallest index in the sorted array where the element is greater than the given number.
Note: If all the elements in the given array are smaller than or equal to the target, the upper bound will be the length of the array.
Examples:
Input: arr[] = [2, 3, 7, 10, 11, 11, 25], target = 9
Output: 3
Explanation: 3 is the smallest index in arr[] at which element (arr[3] = 10) is larger than 9.Input: arr[] = [2, 3, 7, 10, 11, 11, 25], target = 11
Output: 6
Explanation: 6 is the smallest index in arr[] at which element (arr[6] = 25) is larger than 11.Input: arr[] = [2, 3, 7, 10, 11, 11, 25], target = 100
Output: 7
Explanation: As no element in arr[] is greater than 100, return the length of array.
Table of Content
The idea is to use linear search. We compare each element of the given array with the target and find the first index where the element is greater than target.
6
The idea is to use the fact that the given array is sorted. We can apply binary search to find the index of the element just larger than the target.
Step-by-step implementation:
6
We can use built-in functions to find the Upper bound of an element in a sorted array efficiently.
For more details see upper_bound in c++, bisect in python
6
Related Articles: