VOOZH about

URL: https://www.geeksforgeeks.org/dsa/implement-upper-bound/

⇱ Upper Bound - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Upper Bound

Last Updated : 5 Aug, 2025

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.

[Naive Approach] Using Linear Search - O(n) Time and O(1) Space

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.


Output
6

[Expected Approach - 1] Using Binary Search - O(log n) Time and O(1) Space

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:

  1. Set variables lo and hi to the starting and ending of array.
  2. Find mid = (lo + hi) / 2 and compare arr[mid] with target
    => if arr[mid] <= target, then all elements in the range arr[lo...mid] will also be <= target, so update lo = mid+1.
    => if arr[mid] > target, then upper bound will lie in the range arr[lo...mid], so update result to mid and update hi = mid - 1.
  3. Continue step 2 till lo <= hi.
  4. Return result as the upper bound.

Output
6

[Expected Approach - 2] Using Built-In Methods - O(log n) Time and O(1) Space

We can use built-in functions to find the Upper bound of an element in a sorted array efficiently.

  • C++: std::upper_bound(v.begin(), v.end(), x) (from <algorithm>)
  • Python: bisect.bisect_right(arr, x) (from bisect module)

For more details see upper_bound in c++, bisect in python


Output
6

Related Articles:

Comment
Article Tags: