Given a sorted array arr[] and a number target, the task is to 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.
C++
// C++ program to find the upper bound of a number
// using linear search
#include <iostream>
#include <vector>
using namespace std;
int upperBound(vector<int> &arr, int target) {
int n = arr.size();
// Compare target with each element in array
for (int i = 0; i < n; ++i) {
// If larger value found, return its index
if(arr[i] > target) {
return i;
}
}
// If all elements are smaller, return length
return n;
}
int main() {
vector<int> arr = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
cout << upperBound(arr, target);
return 0;
}
C
// C program to find the upper bound of a number
// using linear search
#include <stdio.h>
int upperBound(int arr[], int n, int target) {
// Compare target with each element in array
for (int i = 0; i < n; ++i) {
// If larger value found, return its index
if (arr[i] > target) {
return i;
}
}
// If all elements are smaller, return length
return n;
}
int main() {
int arr[] = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", upperBound(arr, n, target));
return 0;
}
Java
// Java program to find the upper bound of a number
// using linear search
import java.util.*;
class GfG {
// Function to find the upper bound of a number
static int upperBound(int[] arr, int target) {
int n = arr.length;
// Compare target with each element in array
for (int i = 0; i < n; ++i) {
// If larger value found, return its index
if (arr[i] > target) {
return i;
}
}
// If all elements are smaller, return length
return n;
}
public static void main(String[] args) {
int[] arr = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
System.out.println(upperBound(arr, target));
}
}
Python
# Python program to find the upper bound of a number
# using linear search
# Function to find the upper bound of a number
def upperBound(arr, target):
n = len(arr)
# Compare target with each element in array
for i in range(n):
# If larger value found, return its index
if arr[i] > target:
return i
# If all elements are smaller, return length
return n
if __name__ == "__main__":
arr = [2, 3, 7, 10, 11, 11, 25]
target = 11
print(upperBound(arr, target))
C#
// C# program to find the upper bound of a number
// using linear search
using System;
class GfG {
// Function to find the upper bound of a number
static int upperBound(int[] arr, int target) {
int n = arr.Length;
// Compare target with each element in array
for (int i = 0; i < n; ++i) {
// If larger value found, return its index
if (arr[i] > target) {
return i;
}
}
// If all elements are smaller, return length
return n;
}
static void Main() {
int[] arr = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
Console.WriteLine(upperBound(arr, target));
}
}
JavaScript
// JavaScript program to find the upper bound of a
// number using linear search
// Function to find the upper bound of a number
function upperBound(arr, target) {
let n = arr.length;
// Compare target with each element in array
for (let i = 0; i < n; ++i) {
// If larger value found, return its index
if (arr[i] > target) {
return i;
}
}
// If all elements are smaller, return length
return n;
}
let arr = [2, 3, 7, 10, 11, 11, 25];
let target = 11;
console.log(upperBound(arr, target));
[Expected Approach] 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:
- Set variables lo and hi to the starting and ending of array.
- 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.
- Continue step 2 till lo <= hi.
- Return result as the upper bound.
C++
// C++ program to find the upper bound of a number
// using binary search
#include <iostream>
#include <vector>
using namespace std;
int upperBound(vector<int> &arr, int target) {
int lo = 0, hi = arr.size() - 1;
int res = arr.size();
while(lo <= hi) {
int mid = lo + (hi - lo)/2;
// If arr[mid] > target, then arr[mid] can be
// the upper bound so store mid in result and
// search in left half, i.e. arr[lo...mid-1]
if(arr[mid] > target) {
res = mid;
hi = mid - 1;
}
// If arr[mid] <= target, then upper bound
// cannot lie in the range [lo...mid], so
// search in right half, i.e. arr[mid+1...hi]
else
lo = mid + 1;
}
return res;
}
int main() {
vector<int> arr = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
cout << upperBound(arr, target);
return 0;
}
C
// C program to find the upper bound of a number
// using binary search
#include <stdio.h>
// Function to find the upper bound of a number using binary search
int upperBound(int arr[], int n, int target) {
int lo = 0, hi = n - 1;
int res = n;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If arr[mid] > target, then arr[mid] can be
// the upper bound so store mid in result and
// search in left half, i.e. arr[lo...mid-1]
if (arr[mid] > target) {
res = mid;
hi = mid - 1;
}
// If arr[mid] <= target, then upper bound
// cannot lie in the range [lo...mid], so
// search in right half, i.e. arr[mid+1...hi]
else {
lo = mid + 1;
}
}
return res;
}
int main() {
int arr[] = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", upperBound(arr, n, target));
return 0;
}
Java
// Java program to find the upper bound of a number
// using binary search
import java.util.*;
class GfG {
// Function to find the upper bound of a number
static int upperBound(int[] arr, int target) {
int lo = 0, hi = arr.length - 1;
int res = arr.length;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If arr[mid] > target, then arr[mid] can be
// the upper bound so store mid in result and
// search in left half, i.e. arr[lo...mid-1]
if (arr[mid] > target) {
res = mid;
hi = mid - 1;
}
// If arr[mid] <= target, then upper bound
// cannot lie in the range [lo...mid], so
// search in right half, i.e. arr[mid+1...hi]
else {
lo = mid + 1;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 3, 7, 10, 11, 11, 25};
int target = 11;
System.out.println(upperBound(arr, target));
}
}
Python
# Python program to find the upper bound of a number
# using binary search
# Function to find the upper bound of a number
def upperBound(arr, target):
lo, hi = 0, len(arr) - 1
res = len(arr)
while lo <= hi:
mid = lo + (hi - lo) // 2
# If arr[mid] > target, then arr[mid] can be
# the upper bound so store mid in result and
# search in left half, i.e. arr[lo...mid-1]
if arr[mid] > target:
res = mid
hi = mid - 1
# If arr[mid] <= target, then upper bound
# cannot lie in the range [lo...mid], so
# search in right half, i.e. arr[mid+1...hi]
else:
lo = mid + 1
return res
if __name__ == "__main__":
arr = [2, 3, 7, 10, 11, 11, 25]
target = 11
print(upperBound(arr, target))
C#
// C# program to find the upper bound of a number
// using binary search
using System;
class GfG {
static int UpperBound(int[] arr, int target) {
int lo = 0, hi = arr.Length - 1;
int res = arr.Length;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If arr[mid] > target, then arr[mid] can be
// the upper bound so store mid in result and
// search in left half, i.e. arr[lo...mid-1]
if (arr[mid] > target) {
res = mid;
hi = mid - 1;
}
// If arr[mid] <= target, then upper bound
// cannot lie in the range [lo...mid], so
// search in right half, i.e. arr[mid+1...hi]
else {
lo = mid + 1;
}
}
return res;
}
static void Main(string[] args) {
int[] arr = { 2, 3, 7, 10, 11, 11, 25 };
int target = 11;
Console.WriteLine(UpperBound(arr, target));
}
}
JavaScript
// JavaScript program to find the upper bound of
// a number using binary search
// Function to find the upper bound of a number
function upperBound(arr, target) {
let lo = 0, hi = arr.length - 1;
let res = arr.length;
while (lo <= hi) {
let mid = lo + Math.floor((hi - lo) / 2);
// If arr[mid] > target, then arr[mid] can be
// the upper bound so store mid in result and
// search in left half, i.e. arr[lo...mid-1]
if (arr[mid] > target) {
res = mid;
hi = mid - 1;
}
// If arr[mid] < target, then upper bound
// cannot lie in the range [lo...mid], so
// search in right half, i.e. arr[mid+1...hi]
else {
lo = mid + 1;
}
}
return res;
}
let arr = [2, 3, 7, 10, 11, 11, 25];
let target = 11;
console.log(upperBound(arr, target));
Related Articles:
Similar Reads
Implement Lower Bound
Given a sorted array arr[] and a number target, the task is to find the lower bound of the target in this given array. The lower bound of a number is defined as the smallest index in the sorted array where the element is greater than or equal to the given number. Note: If all the elements in the giv
10 min read
Lower and Upper Bound Theory
Lower and upper bound theory is a mathematical concept that involves finding the smallest and largest possible values for a quantity, given certain constraints or conditions. It is often used in optimization problems, where the goal is to find the maximum or minimum value of a function subject to ce
15+ min read
Next Greater Element | Set 2 (Using Upper Bound)
Given an array arr[ ] of n integers. The task is to find the first greater element for every array element in the array using upper_bound( ) function. If there is no greater element possible for any array element return -1. Examples : Input: n = 7, arr[ ] = {4, 7, 3, 1, 3, 2, 5}Output: 7 -1 4 4 4 4
8 min read
Implementation of lower_bound() and upper_bound() in List of Pairs in C++
In this article, we will discuss the implementation of the lower_bound() and upper_bound() in a list of pairs. lower_bound(): It returns an iterator pointing to the first element in the range [first, last) which has a value greater than or equals to the given value âvalâ. But in List of Pairs lower_
3 min read
Implementation of 0/1 Knapsack using Branch and Bound
Given two arrays v[] and w[] that represent values and weights associated with n items respectively. Find out the maximum value subset(Maximum Profit) of v[] such that the sum of the weights of this subset is smaller than or equal to Knapsack capacity Cap(W). Note: The constraint here is we can eith
15+ min read
Sudo Placement | Range Queries
Given Q queries, with each query consisting of two integers L and R, the task is to find the total numbers between L and R (Both inclusive), having almost three set bits in their binary representation. Examples: Input : Q = 2 L = 3, R = 7 L = 10, R = 16 Output : 5 6 For the first query, valid number
13 min read
Program to compare m^n and n^m
Given two positive integers m and n, the task is to write a program that checks whether m^n is greater than, less than, or equal to n^m. Examples : Input: m = 3, n = 10 Output: m^n > n^m Explanation : 3^10=59049 which is greater than 10^3=1000 Input: m = 987654321, n = 123456987 Output: m^n <
4 min read
Traveling Salesman Problem using Branch And Bound
Given a set of cities and distance between every pair of cities, the problem is to find the shortest possible tour that visits every city exactly once and returns to the starting point. For example, consider the graph shown in figure on right side. A TSP tour in the graph is 0-1-3-2-0. The cost of t
15+ min read
Meet in the middle
Given a set of n integers where n <= 40. Each of them is at most 1012, determine the maximum sum subset having sum less than or equal S where S <= 1018. Example: Input : set[] = {45, 34, 4, 12, 5, 2} and S = 42Output : 41Maximum possible subset sum is 41 which can be obtained by summing 34, 5
11 min read
Maximum number of elements that can be taken
Given an array of N integers. Each i'th element increases your sum by a[i], where a[i] can be negative which may decrease your sum. You start with sum=0 and iterate the array from left to right. at each index, you may add the element to your sum or not Your task is to add the maximum number of eleme
7 min read