LeetCode 2774: Array Upper Bound Solution

Master LeetCode problem 2774 (Array Upper Bound), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2774. Array Upper Bound

Easy

Problem Explanation

Explanation

To find the upper bound of a target value in a sorted array, we can use a binary search approach. The idea is to search for the first occurrence of the target value in the array, and then return its index or the index before it in case the target value is not found.

  1. Initialize start = 0 and end = n-1, where n is the number of elements in the array.
  2. Perform a binary search:
    • Calculate mid as the average of start and end.
    • If array[mid] <= target, update start = mid + 1.
    • Otherwise, update end = mid - 1.
  3. After the binary search ends, return end if array[end] == target, or return end - 1 if array[end] < target.

Time Complexity: O(log n)
Space Complexity: O(1)

Solution Code

class Solution {
    public int upperBound(int[] array, int target) {
        int start = 0;
        int end = array.length - 1;

        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (array[mid] <= target) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }

        return (end >= 0 && array[end] == target) ? end : (end - 1);
    }
}

Try It Yourself

Loading code editor...

Frequently Asked Questions

How to solve LeetCode 2774 (Array Upper Bound)?

This page provides optimized solutions for LeetCode problem 2774 (Array Upper Bound) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2774 (Array Upper Bound)?

The time complexity for LeetCode 2774 (Array Upper Bound) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2774 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2774 in Java, C++, or Python.

Back to LeetCode Solutions