Understanding the Problem
We are given a sorted array and a number x
. Our goal is to find the upper bound of x
. That means we want the index of the first element in the array that is strictly greater than x
.
If no element in the array is greater than x
, we should return the size of the array — indicating that all elements are less than or equal to x
.
Step-by-Step Approach
We will use a technique called Binary Search, which is highly efficient on sorted arrays. This approach repeatedly splits the search range in half to quickly find the answer.
Step 1: Define Pointers
- Set
low = 0
(start of the array)
- Set
high = arr.length - 1
(end of the array)
- Set
ans = arr.length
— default to the end of array in case we don’t find a greater element
Step 2: Apply Binary Search Logic
We run a loop while low ≤ high
. On each iteration:
- Calculate the mid index:
mid = Math.floor((low + high) / 2)
- If
arr[mid] > x
:
- It is a valid candidate for upper bound
- So update
ans = mid
- Then try to find a smaller valid index by moving
high = mid - 1
- Else (
arr[mid] ≤ x
):
- We ignore this part of the array and move right:
low = mid + 1
Step 3: Return the Result
After the loop ends, ans
holds the index of the smallest number greater than x
. If all elements are ≤ x
, it remains at arr.length
.
Example Walkthrough
Input: arr = [2, 4, 6, 10, 12]
, x = 6
Expected Output: 3
(since arr[3] = 10
is the first number > 6)
- Initial: low = 0, high = 4, ans = 5
- mid = 2 → arr[2] = 6 → not greater → move right (low = 3)
- mid = 3 → arr[3] = 10 → greater → ans = 3 → check left (high = 2)
- Loop ends → return ans = 3
Handling Edge Cases
- Case 1:
x
is smaller than all elements
Result: returns 0 (first element is upper bound)
- Case 2:
x
is greater than all elements
Result: returns arr.length
(no element is greater)
- Case 3: Array has duplicates
It still finds the first element strictly greater than x
- Case 4: Empty array
Always return 0, as there are no elements to compare
This solution uses binary search, which is optimal for sorted arrays. Instead of checking each element, we skip half the array on each step — making it fast and efficient with a time complexity of O(log n).
Comments
Loading comments...