logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
Calculate Floor & CeilingFind Nth Root Of MFlatten A Linked ListImplement Lower BoundImplement Upper BoundNumber of occurrence
Code Scratch/leetcode/misc

Implement Upper Bound

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

The upper bound of a number x in a sorted array is the index of the first element that is strictly greater than x. If all elements are less than or equal to x, the upper bound is the index n (i.e., where x would go if appended to the array).

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(log⁡N)\text{O}(\log{N})O(logN)

# Code

public static int upperBound(int[] sortedArray, int target, int arrayLength) {
    int left = 0, right = arrayLength - 1;
 
    while (left <= right) {
        int mid = (left + right) >> 1;  // Calculate mid index
 
        // If element equals target, move right to find strictly greater value
        if (sortedArray[mid] == target) {
            while (mid < arrayLength && sortedArray[mid] == target) mid++;
            return mid;
        }
 
        // If middle element is less than or equal to target, move right
        if (sortedArray[mid] < target) {
            left = mid + 1;
        } else {
            // Current mid might be the upper bound, search in left half
            right = mid - 1;
        }
    }
 
    // If no greater element exists, return insertion point (arrayLength)
    return left;
}
 
←PreviousImplement Lower BoundNext→Number of occurrence

On this page

IntuitionComplexityCode