Problem 283

Abstract / Summary

Given an array of integers, move all zero elements to the end while keeping the order of the non-zero elements.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0283.cpp

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int zeros = 0;
        for (auto i = 0; i < nums.size(); i++)
        {
            if (i >= zeros)
                nums[i - zeros] = nums[i];
            if (nums[i] == 0)
                zeros++;
        }

        for (auto i = nums.size() - zeros; i < nums.size(); i++)
            nums[i] = 0;
    }
};
16 lines | 398 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 64% (8+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The moveZeroes member function rearranges the elements of a vector so that all non-zero integers retain their original relative order while all zeros are moved to the end of the container. The operation is performed in place, modifying the input vector directly without allocating additional storage proportional to the input size.

Core Logic

The algorithm begins by initializing a counter named zeros to zero. This counter records how many zero elements have been encountered while scanning the vector from left to right. The first for loop iterates over each index i of the vector. For every position, the code checks whether the current index lies beyond the region already identified as containing zeros (i >= zeros). When this condition holds, the element at position i is copied forward by the number of zeros seen so far, effectively collapsing the non-zero values toward the front of the vector.

int zeros = 0;
for (auto i = 0; i < nums.size(); i++)
{
    if (i >= zeros)
        nums[i - zeros] = nums[i];
    if (nums[i] == 0)
        zeros++;
}

The conditional if (i >= zeros) guarantees that the assignment nums[i - zeros] = nums[i] never overwrites a zero that has not yet been processed. The second if statement increments the zeros counter whenever a zero is encountered, ensuring that subsequent non-zero elements are shifted further left to fill the vacated slots.

Zero Placement Phase

After the first pass, the leading portion of the vector (up to index nums.size() - zeros - 1) contains all original non-zero values in their original order. The remaining zeros positions at the end of the vector may still hold stale values from the original array. The second loop overwrites exactly those trailing positions with zeros, finalizing the transformation.

for (auto i = nums.size() - zeros; i < nums.size(); i++)
    nums[i] = 0;

By calculating the start index as nums.size() - zeros, the loop precisely targets the segment that must be filled with zeros, regardless of how many zeros were present in the original data.

Edge Cases Handled

The implementation gracefully handles several boundary conditions without requiring special-case code. When the input vector contains no zeros, the zeros counter remains zero throughout the first loop; consequently, the second loop’s range becomes empty (nums.size() - 0 equals nums.size()), and no assignments are performed, leaving the vector unchanged. If the vector consists entirely of zeros, the first loop copies each zero onto itself because i - zeros equals i for every iteration, and the zeros counter increments to the vector’s length. The second loop then writes zeros over the entire vector, which is already the case, but the explicit writes guarantee the final state. A single-element vector is also processed correctly: the loops iterate zero or one time as appropriate, and the element is either left untouched (if non-zero) or set to zero (if already zero). The algorithm does not depend on the vector’s size being greater than any particular threshold, making it robust for empty vectors as well; both loops simply skip execution when nums.size() is zero.

Performance Optimizations

The function achieves its goal with a minimal number of passes and without allocating auxiliary containers. The first loop performs both the detection of zeros and the compaction of non-zero elements in a single traversal, eliminating the need for a separate counting phase. By using the zeros counter to compute the target index (i - zeros) on the fly, the algorithm avoids extra indexing structures or temporary buffers. The second loop touches only the exact number of positions that must become zeros, preventing unnecessary writes to elements that are already correctly placed. Because all operations are simple integer comparisons and assignments, the code benefits from strong cache locality; the vector is accessed sequentially in both loops, which aligns well with modern CPU prefetching mechanisms. The in-place nature of the algorithm also reduces memory pressure, making it suitable for environments where allocation overhead must be minimized.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of numbered toy blocks mixed in with some empty spots that look like zeros. The goal is to slide all the numbered blocks to the front of the line and push all the empty zeros to the back while keeping the numbered blocks in the same order.

To do this, the computer looks at each block one by one starting from the beginning. There is a special counter that keeps track of how many zeros have been found so far. Every time a numbered block is spotted, it gets moved forward by shifting it past all the zeros that were found earlier. This keeps the numbered blocks tucked into the front part of the line.

Once the computer reaches the end of the original row, it remembers exactly how many zeros were found. Since those zeros now belong at the very end, the computer goes back to the last few empty spots in the line and fills them each with a zero. Now all the numbers are at the front and all the zeros are nicely grouped at the back just like a perfectly sorted toy box.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 1.35

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
fsq Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt C
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
fsq Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
muhammadfarhankt C
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
zfang399 C++
61 links | 44 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Move Zeroes - Leetcode 283 - Python'
NeetCode 9 mins
Move Zeroes - Leetcode 283 - Python
YouTube video 'How To Move Zeroes To End Of An Array ( LeetCode #283 ) | FREE DSA Course in JAVA | Lecture 67'
TAP ACADEMY 13 mins
How To Move Zeroes To End Of An Array ( LeetCode #283 ) | FREE DSA Course in JAVA | Lecture 67
YouTube video '[Java] Leetcode 283. Move Zeroes [Two Pointers #2]'
Eric Programming 6 mins
[Java] Leetcode 283. Move Zeroes [Two Pointers #2]
YouTube video 'Move zeroes LeetCode Java solution in Hindi ( LeetCode 283 )'
Engineering Digest 4 mins
Move zeroes LeetCode Java solution in Hindi ( LeetCode 283 )
YouTube video 'Move Zeroes || Leetcode 283 || 1 Variant Question Big Tech Actually Asks'
Coding with Minmer 10 mins
Move Zeroes || Leetcode 283 || 1 Variant Question Big Tech Actually Asks
YouTube video 'Leetcode 283. Move Zeroes [ Solution + Code Explained]'
jayati tiwari 8 mins
Leetcode 283. Move Zeroes [ Solution + Code Explained]
YouTube video 'Leetcode | 283. Move Zeroes | Easy | Java Solution'
Developer Docs 5 mins
Leetcode | 283. Move Zeroes | Easy | Java Solution
YouTube video 'Leetcode 283 | Move zeroes | 10th from LC 75 | 90 days SE prep'
Pepcoding 15 mins
Leetcode 283 | Move zeroes | 10th from LC 75 | 90 days SE prep
YouTube video 'Move Zeroes - LeetCode 283 - JavaScript'
AlgoJS 3 mins
Move Zeroes - LeetCode 283 - JavaScript
YouTube video 'MOVE ZEROES | LEETCODE 283 | PYTHON SOLUTION'
Cracking FAANG 9 mins
MOVE ZEROES | LEETCODE 283 | PYTHON SOLUTION
YouTube video 'LeetCode 283 | Move Zeroes | Solution Explained (Java + Whiteboard)'
Xavier Elon 8 mins
LeetCode 283 | Move Zeroes | Solution Explained (Java + Whiteboard)
YouTube video '283. Move Zeroes | LEETCODE INTERVIEW CORNER | LEETCODE | 2 POINTER'
code Explainer 9 mins
283. Move Zeroes | LEETCODE INTERVIEW CORNER | LEETCODE | 2 POINTER
YouTube video 'Leetcode 283: Move Zeroes in telugu | Two Pointer Technique | Python DSA | srkcodes'
Srk Codes 5 mins
Leetcode 283: Move Zeroes in telugu | Two Pointer Technique | Python DSA | srkcodes
YouTube video 'Can You Remove Zeroes? (LeetCode 283: Move Zeroes)'
Code With Zi 6 mins
Can You Remove Zeroes? (LeetCode 283: Move Zeroes)
YouTube video 'LeetCode - 283. Move Zeroes | Two Pointers Technique | Java'
Orkhan Gasanov 4 mins
LeetCode - 283. Move Zeroes | Two Pointers Technique | Java
YouTube video 'LeetCode 283: Move Zeroes | C# Solution | Two Pointer Approach |'
Code Scribbler 7 mins
LeetCode 283: Move Zeroes | C# Solution | Two Pointer Approach |
YouTube video '283. Move Zeroes | Leetcode | Arrays | Fundamentals'
Coding with Tamilarasan 10 mins
283. Move Zeroes | Leetcode | Arrays | Fundamentals
YouTube video 'Move Zeroes - Leetcode 283 - Optimal - JavaScript Solution'
Web Coder Abhishek 5 mins
Move Zeroes - Leetcode 283 - Optimal - JavaScript Solution
YouTube video 'Move Zeroes - Google Interview Questions - LeetCode 283 Solution - C++'
nexTRIE 5 mins
Move Zeroes - Google Interview Questions - LeetCode 283 Solution - C++
YouTube video '283. Move Zeroes (Leetcode Easy)'
Programming Live with Larry 6 mins
283. Move Zeroes (Leetcode Easy)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality