Duplicate zero’s without expanding the array.

Given an array of numbers, you need to duplicate the zero’s in the array. Do not extend the size of array, just discard the remaining elements (had array gets extended, those elements) after the array size.

Example: 

Input: [1, 0, 2, 3, 0, 4, 5, 0]
Output: [1, 0, 0, 2, 3, 0, 0, 4]

Input: [1, 0, 0, 0, 3, 4, 5]
Output: [1, 0, 0, 0, 0, 0, 0]

Input: [1, 2, 3]
Output: [1, 2, 3]

Input: [0, 0, 0]
Output: [0, 0, 0]

Approach:

Initialize previous = null. Now iterate the array from left to right and whenever you encounter 0, set previous = 0 and whenever previous = 0, right shift the array from current index to the last index. Now place 0 at the current index and reset the previous to 0. See the code below for more understanding.

Code: 

Output:

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.