Move Zeroes
Easy
Topics
Given an integer array nums, move all 0's to the end while keeping the relative order of the non-zero elements. Return the resulting array.
Example 1
before
after
Zeros move to the end and everything else keeps its relative order, which rules out swapping with the end. A write pointer that only advances on a non-zero does it in place: copy forward, then fill the tail with zeros.
Shaded cells are the zeros, before and after.
Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0]
Example 2
before
after
Input: nums = [0] Output: [0]
Constraints
- 1 <= nums.length <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
Keep a "write" pointer marking where the next non-zero value belongs. Sliding every non-zero value forward compacts them in order, and the zeros are pushed to the tail for free.
Approach
- Let
j = 0be the slot for the next non-zero. - Scan with
i; whennums[i] != 0, swap it into positionjand advancej. - After the pass,
[0, j)holds the non-zeros in order; the rest are zeros.
Walkthrough
nums = [0, 1, 0, 3]
i=0 (0) skip j=0
i=1 (1) swap -> [1,0,0,3] j=1
i=2 (0) skip j=1
i=3 (3) swap -> [1,3,0,0] j=2Complexity
- Time — O(n): single pass.
- Space — O(1): in place with one index.
Common Pitfalls
- Swap, do not assign. Writing
nums[j] = nums[i]copies the value forward without clearing where it came from, so[0,1,0,3,12]ends up1 3 12 3 12instead of1 3 12 0 0-- the zeros are never written and the tail is duplicated. - Relative order of the non-zero values has to survive, which rules out the two-pointer-from-both-ends trick that works for plain partitioning.
Full Solution — all languages
class Solution:
def moveZeroes(self, nums):
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
return numsimport java.util.*;
class Solution {
public int[] moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int t = nums[j];
nums[j] = nums[i];
nums[i] = t;
j++;
}
}
return nums;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> moveZeroes(vector<int>& nums) {
int j = 0;
for (int i = 0; i < (int)nums.size(); i++) {
if (nums[i] != 0) {
swap(nums[j], nums[i]);
j++;
}
}
return nums;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var moveZeroes = function(nums) {
let j = 0;
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== 0) {
const t = nums[j];
nums[j] = nums[i];
nums[i] = t;
j++;
}
}
return nums;
};