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 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
Find Surpasser Count of each element in array
Given an array of distinct integers arr[], the task is to find the surpasser count for each element of the array. A surpasser of an element in an array is any element to its right that is greater than it, i.e., arr[j] is a surpasser of arr[i] if i < j and arr[i] < arr[j]. The surpasser count o
15 min read
Find Maximum Sum of Mountain Triplets
Given an array A[] of integers. Then the task is to output the maximum sum of a triplet (Ai, Aj, Ak) such that it must follow the conditions: (i < j < k) and (Ai < Aj > Ak). If no such triplet exists, then output -1. Examples: Input: A[] = {1, 5, 4, 7, 3} Output: 15 Explanation: There ar
13 min read
Count elements which divide all numbers in range L-R
The problem statement describes a scenario where we are given an array of N numbers and Q queries. Each query consists of two integers L and R, representing a range of indices in the array. The task is to find the count of numbers in the array that divide all the numbers in the range L-R. Examples :
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
Find the Largest Values From Labels
Given two arrays values[] and labels[] of size n, where values[i] represents the value of the ith item and labels[i] represents the label of the ith item. Additionally, there are two integers numNeeded and limit. The task is to choose a subset s of the n elements such that: The size of the subset s
7 min read