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;
}
};
Difficulty
and has an acceptance rate of about 64% (8+ million submissions).
Typical patterns to solve this problem:
- Array
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 27: Remove Element
- problem 2460: Apply Operations to an Array
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 657: Robot Return to Origin
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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