01
Problem Statement
Given an integer array nums, move all 0's to the end while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array. Minimize the total number of operations.
- All non-zero elements should appear in the same relative order as in the original array. All zeros should be at the end.
- We can do a single pass with a "write" pointer: whenever we see a non-zero, place it at the write position and advance write. Then fill the rest with zeros (or swap to avoid a second pass).
02
Key Observations
- Two pointers:
writepoints to the next position where we should put a non-zero. We scan withread. Whennums[read] != 0, we put it atwrite(swap withnums[write]or just assignnums[write] = nums[read]) andwrite++. After the scan, all non-zeros are in[0..write-1]in order; we can setnums[write..n-1] = 0if we used assign instead of swap. - If we swap, we don't need a second loop: each non-zero is swapped to the front and the zero that was there (if any) goes to the current
readposition and will be processed later.
03
Approach
High-level: write = 0. For each index read: if nums[read] != 0, swap nums[write] and nums[read] (or assign nums[write]=nums[read] and later zero out the tail), then write++. All non-zeros end up in [0..write-1] in order.
Steps:
write = 0. Forread = 0..n-1: ifnums[read] != 0, swapnums[write]andnums[read],write++.- (Optional) For
i = write..n-1, setnums[i] = 0if we used assign instead of swap.
04
Implementation
Java
public void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
if (read != write) {
int t = nums[read];
nums[read] = nums[write];
nums[write] = t;
}
write++;
}
}
}05
Test Cases
Example 1
Input
nums = [0,1,0,3,12]
Expected
[1,3,12,0,0]Explanation
Zeros moved to end.
06
Complexity Analysis
- Time: O(n).
- Space: O(1).
07
Follow-ups
- Move zeros to the front; move a specific value to end.