Duplicate Zeros in Array | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given an array of integers, duplicate each occurrence of zero and shift the remaining elements to the right. Elements beyond the length of the array are dropped (not written).

Note: Implement this with modifications in input array only.

Example 

Duplicate Zeros in Array

Input :- [0, 0, 1, 2, 5, 0, 0, 5, 0]
Output :- [0, 0, 0, 0, 1, 2, 5, 0, 0]
Input :- [1, 1, 1, 0, 0, 0, 0, 5, 0]
Output :- [1, 1, 1, 0, 0, 0, 0, 0, 0]

Solution

The Queue’s FIFO property can be used to solve this problem. We can enqueue all the elements of input array in the queue and then dequeue it one by one and can make modifications.

Following are the steps to solve this problem:

  1. Iterate through the integer array N from start (index 0) to end (n-1, where n is the length of an array) and enqueue each element into the queue Q.
  2. Again iterate through the integer array N and at each iteration dequeue the element from queue Q. If the element is equal to zero, then assign zero to the current and next index of the array and increase the index by 2 and if the element is not equal to zero, then assign the non zero value to the current index and increase the index by 1.

Program

import java.util.LinkedList;
import java.util.Queue;

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int[] data = {1, 1, 1, 0, 0, 0, 0, 5, 0};
		main.duplicateZeros(data);
		for(int i : data) {
			System.out.print(i + ", ");		
		}					
	}
	
	/* Solution */    
	public void duplicateZeros(int[] arr) {
	       
        Queue<Integer> queue = new LinkedList<>();
        for(int i=0; i<arr.length; i++){ 
            queue.add(arr[i]);
        }
        
        int temp;
        for(int i=0; i<arr.length; i++){            
            temp = queue.poll();
            if(temp == 0){
                arr[i] = temp;
                if(i+1<arr.length){
                    arr[i+1] = temp;
                    i++;
                }
            }else {
                arr[i] = temp;
            } 
        }
    }
}

Result

1, 1, 1, 0, 0, 0, 0, 0, 0, 

Similar Post

  1. Find Peak Element in Array
  2. Peak Index in a Mountain Array
  3. Design Min Stack Data Structure

That’s all for Duplicate Zeros in Array in Java, If you liked it, please share your thoughts in a comments section and share it with others too.