Problem
Given a sorted array and an element, find the first occurrence of key in array. As array can contain duplicate values, there can be multiple occurrences of same element, problem is to find first index.
Examples
Example 1:
|
|
Solution
A brute force solution involves scanning the entire array and comparing each A[index]
with the key. If A[index] == key
, return the index. This method has a worst-case time complexity of ( O(N) ). Can we improve this?
The brute force approach doesn’t leverage the fact that the array is sorted. Instead, we can use Binary Search on Sorted Array. When there are no duplicates, finding the first instance with binary search is straightforward. How can we adapt this for arrays with duplicates?
Method 1 - Binary Search Variant
If target == a[mid]
, update firstPosition
to mid
. However, to find the very first occurrence of the target
, continue checking the left part of the array for a lower position where the target
might appear.
Code
|
|