Given a sorted array of integers and a target number key
, your task is to find the first occurrence (leftmost index) of key
in the array.
If the element is not found, return -1
.
public class FirstOccurrenceFinder {
public static int solve(int n, int key, int[] v) {
int start = 0;
int end = n - 1;
int res = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (v[mid] == key) {
res = mid; // Record the index
end = mid - 1; // Move left to check if it occurs earlier
} else if (key < v[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {5, 10, 10, 10, 20, 20};
int key = 10;
int result = solve(arr.length, key, arr);
System.out.println("First Occurrence Index: " + result);
}
}
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | The key is found at the mid index in the first iteration. |
Average Case | O(log n) | Binary search reduces the search space by half each time. |
Worst Case | O(log n) | All elements must be checked in the narrowed space to find the first occurrence. |