Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Implement Upper Bound
    Data Structures & Algorithms

    Implement Upper Bound

    codeanddebugBy codeanddebug2 July 2025No Comments3 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Featured image of question to implement upper bound
    Share
    Facebook Twitter LinkedIn Pinterest Email

    In a sorted array arr[], the upper bound of x is the index of the first element that is strictly greater than x.
    If every element in the array is ≤ x, the conventional upper-bound position is n (one past the last index).

    Here’s the [Problem Link] to begin with.

    Example
    arr = [1, 2, 4, 4, 6], x = 4
    Upper bound → index 4 (value 6), because indices 0–3 are ≤ 4 and index 4 is the first > 4.

    Upper-bound queries power range searches, frequency counts, and insertion-point calculations. A tailored binary-search achieves this in logarithmic time.

    Contents:
     [show]
    • Optimal Solution (Binary Search)
      • Intuition & Approach
      • Code Implementation
      • Code Explanation
      • Dry Run (arr = [1, 2, 4, 4, 6], x = 4)
      • Time & Space Complexity
      • Conclusion

    Optimal Solution (Binary Search)

    Intuition & Approach

    1. Search Window – Maintain two pointers, low and high, around the current candidate range.
    2. Potential Answer Tracker – Keep ub, the best upper-bound index seen so far, initialised to n (meaning “not found yet”).
    3. Binary Search Loop
      • Compute mid.
      • If arr[mid] > x, mid is a valid upper bound. Save it in ub and continue searching left (smaller indices) for an even earlier position.
      • Otherwise (arr[mid] ≤ x) move low right to discard non-qualifying elements.
    4. When the loop terminates, ub holds either the first index of an element > x or n if such an element doesn’t exist.

    Code Implementation

    def upperBound(arr: [int], x: int, n: int) -> int:
        n = len(arr)                 # total number of elements
        ub = n                       # default upper bound (past-the-end)
        low, high = 0, n - 1         # binary-search boundaries
    
        while low <= high:
            mid = (low + high) // 2  # midpoint of current window
    
            if arr[mid] > x:
                ub = mid             # arr[mid] is a better (earlier) upper bound
                high = mid - 1       # search the left half for an even smaller index
            else:                    # arr[mid] <= x → discard left half including mid
                low = mid + 1        # shift window right to find a greater element
    
        return ub                    # final upper-bound index (or n if none)
    Python

    Code Explanation

    • ub = n acts as a sentinel meaning “no upper bound found yet.”
    • Case arr[mid] > x
      • mid itself qualifies. Store it and shrink the window leftward to see if an earlier qualifying index exists.
    • Case arr[mid] <= x
      • All indices ≤ mid are ≤ x, so the next valid upper bound must be to the right.
    • Loop ends when low crosses high; at that point every potential position is checked and ub is final.

    Dry Run (arr = [1, 2, 4, 4, 6], x = 4)

    Steplowhighmidarr[mid]ub updateNext Window
    10424— (still 5)low = 3
    23434— (still 5)low = 4
    34446ub = 4high = 3
    End————ub = 4loop stops

    Result 4, matching the expected upper-bound index.

    Time & Space Complexity

    • Time: O(log n) — each iteration halves the search space.
    • Space: O(1) — only a few integer variables are used.

    Conclusion

    By slightly tweaking classic binary search, tracking the last “good” index, we can compute the upper bound in logarithmic time and constant space. This pattern generalises to numerous “first/last element with property P” queries on sorted data. Happy coding!

    Join our Advance DSA COURSE

    For any changes to the article, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Array Binary Search
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleImplement Lower Bound | Floor in a Sorted Array (GFG)
    Next Article Search Insert Position | Leetcode 35 | Explained in Python
    codeanddebug
    • Website

    Related Posts

    Data Structures & Algorithms

    Search in Rotated Sorted Array | Leetcode 33 | Optimal Binary Search

    3 July 2025
    Data Structures & Algorithms

    Count occurrences of a number in a sorted array with duplicates | Optimal Binary Search

    3 July 2025
    Data Structures & Algorithms

    Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search

    2 July 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • Data Structures & Algorithms (93)
      • Beginner (44)
      • Expert (22)
      • Intermediate (27)
    • Uncategorised (1)
    Recent Posts

    Search in Rotated Sorted Array | Leetcode 33 | Optimal Binary Search

    3 July 2025

    Count occurrences of a number in a sorted array with duplicates | Optimal Binary Search

    3 July 2025

    Find First and Last Position of Element in Sorted Array | Leetcode 34 | Optimal Binary Search

    2 July 2025

    Ceil The Floor | Binary Search Implementation

    2 July 2025

    Search Insert Position | Leetcode 35 | Explained in Python

    2 July 2025
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.