Move Zeros
Easy
ArrayTwo Pointers
Problem
Given an integer array nums, move all zeros to the end while keeping the relative order of the non-zero elements. Do it in-place.
Example 1
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2
Input: nums = [0]
Output: [0]
Constraints
- 1 ≤ nums.length ≤ 10⁴
- −2³¹ ≤ nums[i] ≤ 2³¹ − 1
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
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 nums
Java
class Solution {
public void moveZeroes(int[] nums) {
int write = 0;
// First pass: write every non-zero compactly from the front.
for (int num : nums) {
if (num != 0) {
nums[write++] = num;
}
}
// Second pass: fill the rest with zeros.
while (write < nums.length) {
nums[write++] = 0;
}
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Move Zeros interactively → ← All solutions