Topic Contents
Problem Statement
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
.
⬅ Previous Topic
Floor and Ceil in Sorted ArrayTopic Contents
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
.
start = 0
, end = n - 1
, and res = -1
to store the result.start ≤ end
, calculate mid = start + (end - start) / 2
.arr[mid] == key
: update res = mid
and move end = mid - 1
to search left.arr[mid] < key
: move start = mid + 1
.arr[mid] > key
: move end = mid - 1
.res
will contain the first occurrence index or -1 if not found.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. |
Average Case | O(log n) | All elements must be checked in the narrowed space to find the first occurrence. |
O(1)
Explanation: The algorithm uses only a fixed number of variables regardless of input size.
Next Topic ⮕
Last Occurrence in a Sorted ArrayMention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.