Problem
Given a sorted array and an element, find last occurrence of element in array.
Examples
Example 1:
| |
This problem is similar to Find first position of target element in sorted array.
Solution
A brute force solution involves scanning the entire array and comparing each A[index] with the key. If A[index] is equal to the key and the next element is different, return the index. The worst-case time complexity of this method is ( O(N) ). Can we improve this?
And the answer is yes, using Binary Search on Sorted Array.
Method 1 - Binary Search
If target == a[mid], update lastPosition to mid. However, to find the very last occurrence of the target, continue checking the right part of the array to see if the target appears at a higher position.
Code
| |