This is the Move Zeroes problem. Copy every non-zero value forward to a write position, then fill the remaining positions with zeros. The non-zero values keep their original order.
import java.util.Arrays;
public class MoveZeroes {
static void moveZeroes(int[] nums) {
int k = 0;
for (int num : nums) {
if (num != 0) {
nums[k++] = num;
}
}
while (k < nums.length) {
nums[k++] = 0;
}
}
public static void main(String[] args) {
int[] nums = {0, 1, 0, 3, 12, 0, 5};
moveZeroes(nums);
System.out.println(Arrays.toString(nums));
}
}[1, 3, 12, 5, 0, 0, 0]
Sorting would not work here: it changes the order of the non-zero values and costs O(n log n).
State the constraints you are meeting (in place, order preserved, O(n)) before coding; this problem is mostly about meeting them.
A concise interview answer is
I keep a write index and copy each non-zero value forward, which preserves their order, then fill the rest of the array with zeros. It runs in O(n) time with O(1) extra space and modifies the array in place.
Last updated: 11 November 2026
Previous question: Write a function to check whether an integer is a power of two.
Next question: Find all numbers from 1 to n that are missing from an array.