Move Zeroes to End of Array | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given an array of integers, write a program to move all 0 to the end of the array while maintaining the relative order of the non zero elements.

Note: Implement with O(1) space complexity (in-place)

Example 

Move Zeroes to End of Array

Input :- [0, 1, 0, 3, 12, 11, 0, 8, 0]
Output :- [1, 3, 12, 11, 8, 0, 0, 0, 0]
Input :- [1, 0, 0, 0, 9, 8, 0, 7, 0]
Output :- [1, 9, 8, 8, 0, 0, 0, 0, 0]

Solution

To solve this problem, we can use Two pointer approach where one pointer will always be at the end of non zero part of the array and another pointer will always be at zero part of an array.

This problem can be solved in following steps :-

  1. Create two variables first and second with initial values as 0 and 1 respectively.
  2. Traverse the given input array until the second variable reaches the end of the array.
  3. If the first variable points to non zero value and the second variable points to zero value, then swap their values and move both of them to right by 1. Otherwise 
  4. If both first and second variable points to zero value, then move only the second variable to right by 1.
  5. In any other case, move both of them to right by 1.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int[] result = main.moveZeroes(new int[] {1, 0, 0, 0, 9, 8, 0, 7, 0});
		for(int i : result) {
			System.out.print(i + ", ");
		}		
	}
	
	/* Solution */    
	public int[] moveZeroes(int[] nums) {
        
        int first = 0;
        int second = 1;
        int temp;        
        while(second < nums.length){            
            if(nums[first] == 0 && nums[second] != 0){
                temp = nums[second];
                nums[second] = nums[first];
                nums[first] = temp;
                first++;
                second++;
            }else if(nums[first] == 0 && nums[second] == 0){
                second++;
            }else {
                first++;
                second++;
            }            
        }
        return nums;
    }
}

Result

1, 9, 8, 8, 0, 0, 0, 0, 0, 

Similar Post

  1. Find Pivot Index in Array
  2. Rotate Array
  3. Maximum Subarray

That’s all for Move Zeroes to End of Array in Java, If you liked it, please share your thoughts in a comments section and share it with others too.