Learn-dsa..in 30 days!



























CC-15 : Remove consecutive duplicates from array.

Description:

Given an input integer array, return consecutive duplicate integers from the same.

Test cases and expected outputs:

Input Parameters Expected outputs
Original array : 1,2,2,1,4,7,2,1 Cons Dups removed : 4,7,2,1
Original array : 8,3,2,3,3,1,1,4 Cons Dups removed : 8,3,2,4

Pseudocode:

Initialize a Deque based stack for processing purposes.
For each integer in input array:
If stack size is not zero and top element of stack is same as current element of array, remove top element of stack.
Else add current element of array to stack.
Convert the stack to array and reverse elements of array to get output array in same order as input array with consecutive duplicates removed.


Code:

public int[] removeConsequtiveDuplicates(int[] arr) throws Exception{
	Deque<Integer> stack=new LinkedList<Integer>();
	int i;
	for (int idx=0; idx< arr.length;idx++) {
		i=arr[idx];
		if ((stack.size()!=0)&&(stack.peekFirst()==i)){
			stack.pollFirst();
		}else {
			stack.offerFirst(i);
		}
	}
	Integer[] retVal1=stack.toArray(new Integer[0]);
	int[] retVal2=new int[retVal1.length];
	for (int idx=0; idx< retVal1.length;idx++) {
		retVal2[retVal1.length-idx-1]=retVal1[idx];
	}
	return retVal2;	
}

Click here to download and run code and test cases !