Learn-dsa..in 30 days!



























CC-20 : Remove all instances of number from array in place.

Description:

Given input integer array arr, and integer num, remove all instances of num from arr. At end of the processing, all elements of arr that are not equal to num should be at the startng indexes of the array. If k instances of num are removed, last n instances of arr should be 0.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,2,2,6,7}
num=2
1,7,3,6,0,0,0
arr{ 0,-1,-2,-3,0}
num=0
-3,-1,-2,0,0
arr={-33,-33,-4,0,77,21,67,-33}
num=-33
67,21,-4,0,77,0,0,0
arr={5} num=5 0

Pseudocode:

The java method should accept following input parameters: arr (int array) and integer num.
Initialise two int variables sIdx=0 (start Index) and eIdx =arr.length-1(end Index).
Iterate the array using while loop while sIdx <= eIdx:
If arr[sIdx] !=num; nothing to be done just increment sIdx and continue to next iteration.
If arr[eIdx]==num;set arr[eIdx] to 0, decrement eIdx and continue to next iteration.
If arr[sIdx]==num:
Set arr[sIdx] to arr[eIdx].
Set arr[eIdx] to 0.
Increment sIdx and decrement eIdx.
At end of while loop all instances of num will be removed and empty indices will be filled with Os at end of arr. Return arr.

Code:

public int[] arrayRemoveNumber(int[] arr, int num) throws Exception{
	int sIdx=0; int eIdx=arr.length-1;
	while (sIdx <= eIdx) {
		if (arr[sIdx] != num) {
			sIdx++; continue; 
		}
		if (arr[eIdx]==num) {
			arr[eIdx]=0;
			eIdx--; continue;
		}
		if (arr[sIdx] == num) {
			arr[sIdx]=arr[eIdx];
			arr[eIdx]=0;
			sIdx++;
			eIdx--;
		}		
	}
	return arr;
}

Click here to download and run code and test cases !