Input:
10, 20, 20, 20, 20, 20, 40, 50, 50, 60
20
Output:15
package jan21;
public class FirstLastIndex {
public static void main(String[] args) {
int[] arr = {10, 20, 20, 20, 20, 20, 40, 50, 50, 60};
int data = 20;
int low = 0, high = arr.length - 1, firstIndex = -1, lastIndex = -1;
// -----------------------
// Find First Index
// -----------------------
// Time Complexity: O(log n)
// Space Complexity: O(1)
// Binary search to find first occurrence of 'data'
while (low <= high) {
int mid = low + (high - low) / 2;
if (data > arr[mid]) {
low = mid + 1;
} else if (data < arr[mid]) {
high = mid - 1;
} else {
firstIndex = mid; // potential first index found
high = mid - 1; // move left to find earlier occurrence
}
}
System.out.println(firstIndex);
// -----------------------
// Find Last Index
// -----------------------
low = 0;
high = arr.length - 1;
lastIndex = -1;
// Time Complexity: O(log n)
// Space Complexity: O(1)
// Binary search to find last occurrence of 'data'
while (low <= high) {
int mid = low + (high - low) / 2;
if (data > arr[mid]) {
low = mid + 1;
} else if (data < arr[mid]) {
high = mid - 1;
} else {
lastIndex = mid; // potential last index found
low = mid + 1; // move right to find later occurrence
}
}
System.out.println(lastIndex);
}
}
📊 Complexity Table
Case Time Complexity Space Complexity Description Best O(log n)O(1)Binary search immediately finds the element on first try Average O(log n)O(1)Standard binary search behavior, divides the array in halves Worst O(log n)O(1)Element occurs multiple times (as in your example), so both full searches needed
No comments:
Post a Comment