Problem
Write code that enhances all arrays such that you can call the upperBound()
method on any array and it will return the last index of a given target
number. nums
is a sorted ascending array of numbers that may contain duplicates. If the target
number is not found in the array, return -1
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= nums.length <= 10^4
-10^4 <= nums[i], target <= 10^4
nums
is sorted in ascending order.
Follow up: Can you write an algorithm with O(log n) runtime complexity?
Solution
Method 1 – Binary Search 1
Intuition
Since the array is sorted, we can use binary search to efficiently find the last occurrence of the target. Binary search helps us skip over large sections of the array, making the search much faster than a linear scan.
Approach
- Set two pointers,
l
(left) andr
(right), to the start and end of the array. - While
l
is less than or equal tor
:- Find the middle index
m
. - If
nums[m]
is less than or equal totarget
, movel
tom + 1
(search right side). - Otherwise, move
r
tom - 1
(search left side).
- Find the middle index
- After the loop, check if
r
is within bounds andnums[r]
equalstarget
. - If so, return
r
(last index of target). Otherwise, return-1
.
JavaScript
|
|
TypeScript
|
|
Complexity
- ⏰ Time complexity: O(log n)
- 🧺 Space complexity: O(1)