Java Program to Move Zeros to End of Array
Examples
How to Think About It
Algorithm
Code
public class MoveZeros { public static void moveZerosToEnd(int[] arr) { int index = 0; // position for next non-zero for (int num : arr) { if (num != 0) { arr[index++] = num; } } while (index < arr.length) { arr[index++] = 0; } } public static void main(String[] args) { int[] arr = {0, 1, 0, 3, 12}; moveZerosToEnd(arr); for (int num : arr) { System.out.print(num + " "); } } }
Dry Run
Let's trace the array [0, 1, 0, 3, 12] through the code
Initialize index
index = 0
Check first element (0)
0 is zero, do nothing, index stays 0
Check second element (1)
1 is not zero, place at arr[0], index becomes 1, array now [1, 1, 0, 3, 12]
Check third element (0)
0 is zero, do nothing, index stays 1
Check fourth element (3)
3 is not zero, place at arr[1], index becomes 2, array now [1, 3, 0, 3, 12]
Check fifth element (12)
12 is not zero, place at arr[2], index becomes 3, array now [1, 3, 12, 3, 12]
Fill remaining with zeros
arr[3] = 0, arr[4] = 0, final array [1, 3, 12, 0, 0]
| Iteration | Current Element | Index | Array State |
|---|---|---|---|
| 1 | 0 | 0 | [0, 1, 0, 3, 12] |
| 2 | 1 | 1 | [1, 1, 0, 3, 12] |
| 3 | 0 | 1 | [1, 1, 0, 3, 12] |
| 4 | 3 | 2 | [1, 3, 0, 3, 12] |
| 5 | 12 | 3 | [1, 3, 12, 3, 12] |
| Fill zeros | - | 5 | [1, 3, 12, 0, 0] |
Why This Works
Step 1: Collect non-zero elements
The code moves through the array and copies each non-zero element to the front, keeping their order with arr[index++] = num.
Step 2: Fill zeros at the end
After placing all non-zero elements, the remaining positions are filled with zeros using a while loop.
Step 3: In-place modification
The array is changed directly without extra arrays, making it efficient in space.
Alternative Approaches
public class MoveZeros { public static void moveZerosToEnd(int[] arr) { int[] temp = new int[arr.length]; int index = 0; for (int num : arr) { if (num != 0) { temp[index++] = num; } } while (index < arr.length) { temp[index++] = 0; } for (int i = 0; i < arr.length; i++) { arr[i] = temp[i]; } } }
public class MoveZeros { public static void moveZerosToEnd(int[] arr) { int lastNonZeroFoundAt = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] != 0) { int temp = arr[lastNonZeroFoundAt]; arr[lastNonZeroFoundAt] = arr[i]; arr[i] = temp; lastNonZeroFoundAt++; } } } }
Complexity: O(n) time, O(1) space
Time Complexity
The algorithm loops through the array once, so it runs in linear time relative to the array size.
Space Complexity
It modifies the array in place using only a few extra variables, so space is constant.
Which Approach is Fastest?
The in-place method with a single pass is fastest and most memory efficient compared to using extra arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| In-place overwrite | O(n) | O(1) | Memory efficiency and speed |
| Extra array | O(n) | O(n) | Simplicity and clarity |
| Swapping zeros | O(n) | O(1) | Minimizing writes, preserving order |