Open In App

Implement Upper Bound

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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));

Output
6

[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:

  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.
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));

Output
6

Related Articles:


Next Article

Similar Reads