Learn-dsa..in 30 days!



























CC-1 : Find first and last index of given number in an array.

Description:

Given an input integer array "arr" and an integer "searchInt", find the first and last index of searchInt in arr.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4,5,6,7,1}, searchInt=1 firstIdx=0, lastIdx=7
arr={1,2,3,4,5,6,7,1}, searchInt=3 firstIdx=2, lastIdx=2
arr={1,2,3,4,5,6,7,1}, searchInt=11 firstIdx=-1, lastIdx=-1

Asked by: , , , Leetcode #34

Summary Algorithm:

Initialize two tracking variables to -1 and iterate through the entire array to locate the specified target value. When a match is found, the algorithm records the index as the first occurrence if it hasn't been set yet and continually updates the last occurrence index until the loop finishes.

Pseudocode:

The method should accept following input parameters: arr (int array), searchInt (integer to be searched in arr).
Initialize 2 variables firstIdx and lastIdx to -1. We will use these variables to track the first and last index of searchInt in arr.
Iterate through arr using a for loop, using variable idx as loop counter:
If searchInt is found for first time set firstIdx and lastIdx to the index at which it was found.
If searchInt is found again in any iteration just update lastIdx to the index at which it was found.
Add firstIdx and lastIdx to an integer array and return the same.

Code:

public int[] arrayFindFirstAndLastIndexOfElement(int[] arr,int searchInt) throws Exception{
	int firstIdx=-1;
	int lastIdx=-1;
	for (int idx=0; idx < arr.length; idx++) {
		if (arr[idx] == searchInt) {
			if (firstIdx==-1) {
				firstIdx=idx;
				lastIdx=idx;
			}else {
				lastIdx=idx;
			}				
		}			
	}
	int[] idxFound=new int[2];
	if (firstIdx==-1) {
		idxFound[0]=idxFound[1]=-1;
	}else {
		idxFound[0]=firstIdx;
		idxFound[1]=lastIdx;
	}
	return idxFound;			
}
Time Complexity Space Complexiy
O(n) O(1)

Click here for execution trace to understand the code better.

Click here to download and run code and test cases !