283. Move Zeroes
Easy ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Two Pointers
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven an integer array, rearrange it in-place so all zeros are moved to the end while the relative order of non-zero elements is preserved, without returning anything.
Approach
- Maintain a
writepointer that tracks the next position where a non-zero element should land. - Scan through the array with a
readpointer; whenever a non-zero value is found, swap it into thewriteposition and advancewrite. - Because every non-zero element is swapped into the earliest available slot, their original relative order is maintained and all displaced zeros accumulate at the tail.
- One pass suffices, making the algorithm O(n) time and O(1) space.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int write = 0; // next slot for a non-zero element
for (int read = 0; read < (int)nums.size(); ++read) {
if (nums[read] != 0) {
// Swap instead of overwrite: zeros naturally migrate right
swap(nums[write], nums[read]);
++write;
}
}
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int slow=0;
for(int fast=0; fast<nums.size(); ++fast){
if(nums[fast]!=0){
if(slow!=fast){
std::swap(nums[slow], nums[fast]);
}
++slow;
}
}
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.