Java Program to Move All Zeros to the Start of an Array

Moving all zeros to the start of an array in Java can be achieved using various methods. Here, we will explore three different approaches: using an auxiliary array, in-place swapping, and the two-pointer technique. Each method will be explained and accompanied by complete Java code.

Method 1: Using an Auxiliary Array

This method involves creating an additional array to store the zeros and non-zero elements separately.

File Name: MoveZerosToStart.java

Output:

 
[0, 0, 0, 1, 2, 3, 4]   

Explanation

In the auxiliary array method, we traverse the array three times. First, we count the zeros and place them in the new array. Second, we place the non-zero elements in the new array.

Finally, we copy the new array back to the original array. Despite these multiple passes, each traversal is linear, making the overall time complexity 𝑂(𝑛) where n is the length of the array. This approach is simple but requires additional space proportional to the array size.

Method 2: In-Place Swapping

This approach minimizes space complexity by swapping zeros to the front of the array in-place.

File Name: MoveZerosToStart.java

Output:

 
[0, 0, 0, 1, 2, 3, 4]   

Explanation

In this method, we traverse the array once, swapping zeros to the front whenever encountered. This is done by maintaining an index to place zeros and swapping it with the current element if it's a zero.

As we only traverse the array once and perform constant-time swaps, the time complexity is O(n) for the best, worst, and average cases. The space complexity is O(1) since we only use a few extra variables for indexing.

Method 3: Two-Pointer Technique

This method uses two pointers to efficiently move zeros to the start of the array without extra space.

File Name: MoveZerosToStart.java

Output:

 
[0, 0, 0, 1, 2, 3, 4]   

Explanation

In this method, we use two pointers starting from opposite ends of the array. One pointer moves from the left to find non-zero elements, and the other moves from the right to find zeros. When a zero is found on the right and a non-zero element on the left, they are swapped.

It continues until the pointers meet. Each element is processed at most once, resulting in a time complexity of O(n)for the best, worst, and average cases. The space complexity is O(1) as only a few extra variables are used.

Conclusion

All three methods exhibit a linear time complexity of O(n) in the best, worst, and average cases. However, the auxiliary array method uses additional space proportional to the array size, while the in-place swapping and two-pointer techniques operate with constant space complexity O(1). Therefore, the in-place and two-pointer techniques are generally more space-efficient.