Move zeroes to the end of an array in place while preserving the order of nonzero values. Learn the two-pointer solution in Java and Python.
Problem and input contract
Pass a mutable sequence of integers. Both implementations modify it in place and return no value. The sequence retains its original length, with all nonzero values in their original relative order.
[0, 3, 0, 2] becomes [3, 2, 0, 0]. [0, 0] and [-2, 4] stay unchanged. An empty array remains empty.
Worked example
[0, 3, 0, 2] becomes [3, 2, 0, 0].
Skip the first 0. Copy 3 into index 0, skip the next 0, then copy 2 into index 1. At that point write is 2, so fill indices 2 and 3 with zero.
How the solution works
The write index never moves ahead of the read index. Every nonzero value is copied forward in encounter order, then the remaining cells are filled with zeros.
Each write lands at or before the position being read. This keeps unread values intact and preserves the original order of the nonzero numbers.
Python solution
def move_zeroes(nums):
write = 0
for value in nums:
if value != 0:
nums[write] = value
write += 1
for index in range(write, len(nums)):
nums[index] = 0Java solution
class Solution {
static void moveZeroes(int[] nums) {
int write = 0;
for (int value : nums) {
if (value != 0) nums[write++] = value;
}
while (write < nums.length) nums[write++] = 0;
}
}Approaches and complexity
You can build a separate list of nonzero values and copy it back before filling zeros, using O(n) temporary storage. The two-pointer solution has one pass over the input followed by a pass over the tail, taking O(n) time and O(1) auxiliary space.
| Approach | Time | Auxiliary space | Advantage | Limitation | Use case |
|---|---|---|---|---|---|
| Temporary list | O(n) | O(n) | Straightforward | Stores a second sequence | Memory is plentiful |
| Two pointers | O(n) | O(1) | In-place and stable | May rewrite some cells | Memory-constrained inputs |
Common mistakes and interview follow-up
Advance the write index only when keeping a value. Filling the suffix after the scan prevents unread values from being overwritten. If writes are expensive, discuss how to skip self-assignments.
Related practice: Find Two Numbers That Add to a Target.
Comments
Post a Comment