Tuesday, May 20, 2025

First and Last Index

 Input: 

10, 20, 20, 20, 20, 20, 40, 50, 50, 60
20

Output:
1
5

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

CaseTime ComplexitySpace ComplexityDescription
BestO(log n)O(1)Binary search immediately finds the element on first try
AverageO(log n)O(1)Standard binary search behavior, divides the array in halves
WorstO(log n)O(1)Element occurs multiple times (as in your example), so both full searches needed

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...