Move Zeroes
Problem
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
nums = [4, 0, 2, 0, 5, 0, 1][4, 2, 5, 1, 0, 0, 0]def move_zeroes(nums):
w = 0
for r in range(len(nums)):
if nums[r] != 0:
nums[w], nums[r] = nums[r], nums[w]
w += 1
return nums
function moveZeroes(nums) {
let w = 0;
for (let r = 0; r < nums.length; r++) {
if (nums[r] !== 0) {
[nums[w], nums[r]] = [nums[r], nums[w]];
w++;
}
}
return nums;
}
class Solution {
public int[] moveZeroes(int[] nums) {
int w = 0;
for (int r = 0; r < nums.length; r++) {
if (nums[r] != 0) {
int tmp = nums[w]; nums[w] = nums[r]; nums[r] = tmp;
w++;
}
}
return nums;
}
}
vector<int> moveZeroes(vector<int>& nums) {
int w = 0;
for (int r = 0; r < (int)nums.size(); r++) {
if (nums[r] != 0) {
swap(nums[w], nums[r]);
w++;
}
}
return nums;
}
Explanation
The goal is to push every 0 to the back while keeping the non-zero numbers in their original order. We do this in place with two pointers: a read pointer r that scans the whole array and a write pointer w that marks where the next non-zero value belongs.
Walk r across the array. Whenever nums[r] is non-zero, swap it into position w and bump w forward. Zeros are simply skipped, so they naturally drift toward the end.
Because w only advances on non-zeros, everything before w stays a tightly packed, order-preserving run of the non-zero values, and the swaps quietly send the zeros to the back.
Example: nums = [4, 0, 2, 0, 5, 0, 1]. The 4 swaps with itself, then 2, 5, and 1 each get packed to the front in order, leaving [4, 2, 5, 1, 0, 0, 0].
This is a single O(n) pass using no extra array, just two index variables.