Algo-Sim › Two Pointers
Move Zeroes
Easy · Two Pointers · step through it in Java, Python and C++ on your own input
Move every 0 to the end in place, keeping the other values in their original order.
Problem
Given an integer array nums, move every 0 to the end of the array while keeping the non-zero values in their original relative order. Do it in place, without copying the array.
Constraints
- 1 ≤ nums.length ≤ 10⁴
- -2³¹ ≤ nums[i] ≤ 2³¹ − 1
- In place; follow-up: minimise the number of writes
Edge cases to test
- No zeros
- All zeros
- Zeros already at the end
Follow-up questions
- How do you minimise the number of writes?
- Swap each non-zero with the first zero slot instead of writing then filling zeros: writes only where values move.
- Is the order of the non-zeros kept?
- Yes: the slow pointer writes them in their original order, so the partition is stable, unlike a quicksort-style partition.
Solution
Java
public void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
int tmp = nums[write];
nums[write] = nums[read];
nums[read] = tmp;
write++;
}
}
}Python
def move_zeroes(nums):
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int> &nums) {
int write = 0;
for (int read = 0; read < int(nums.size()); read++) {
if (nums[read] != 0) {
int tmp = nums[write];
nums[write] = nums[read];
nums[read] = tmp;
write++;
}
}
}
};
More Two Pointers problems
- Valid Palindrome (Easy)
- Valid Palindrome II (Easy)
- Two Sum II - Input Array Is Sorted (Medium)
- Remove Duplicates from Sorted Array (Easy)
- Container With Most Water (Medium)
- Trapping Rain Water (Hard)
- Sort Colors (Medium)
- Merge Sorted Array (Easy)
- Rotate Array (Medium)
- Next Permutation (Medium)
- 3Sum (Medium)