C++ 1089.cpp
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
vector<int> two;
for (auto x : arr)
{
two.push_back(x);
if (x == 0)
two.push_back(0);
if (two.size() > arr.size())
break;
}
two.resize(arr.size());
arr = move(two);
}
};
Difficulty
and has an acceptance rate of about 53% (900k+ 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 presented implementation defines a duplicateZeros method that receives a mutable reference to a vector<int> and modifies it so that every zero in the original sequence is duplicated, while the overall length of the container remains unchanged. The algorithm constructs a temporary vector, populates it according to the duplication rule, truncates it to the original size, and finally transfers ownership back to the input vector using move semantics. The design emphasizes a single forward pass, early termination when the output would exceed the allowed length, and efficient memory handling through move assignment.
Core Logic
The function begins by declaring an auxiliary container named two. This container will hold the intermediate result while the original vector is being examined.
vector<int> two;
A range-based for loop iterates over each element of the source vector arr. For every element x, the algorithm first appends x to two. If x equals zero, a second zero is appended immediately after the first, thereby achieving the duplication effect.
for (auto x : arr)
{
two.push_back(x);
if (x == 0)
two.push_back(0);
After each insertion, the code checks whether the size of two has grown beyond the capacity of the original vector. As soon as this condition becomes true, the loop terminates, preventing any further elements from being processed.
if (two.size() > arr.size())
break;
}
Once the loop finishes, two may be longer than the allowed length. The resize call trims the auxiliary vector to exactly match the size of arr.
two.resize(arr.size());
Finally, the original vector is replaced by the contents of two through a move operation. This transfers the internal storage of two to arr without copying each element, leaving two in a valid but unspecified state.
arr = move(two);
Edge Cases Handled
The algorithm gracefully accommodates several boundary conditions without additional branching:
-
Empty Input - When
arrcontains no elements, the range-based loop executes zero times. The auxiliary vector remains empty,resizeis a no-op, and the move assignment leavesarrunchanged. -
All Zeros - If every element of
arris zero, each iteration attempts to insert two zeros. The early-exit condition (two.size() > arr.size()) stops the loop precisely when the output would exceed the original length, ensuring that the final vector contains as many duplicated zeros as can fit. -
Zero at the End - When a zero appears near the tail of the array, the duplication may push the size beyond the limit. The break statement prevents the extra zero from being added, preserving the required length while still duplicating earlier zeros.
-
Single-Element Vector - For a vector of length one, the loop processes the sole element. If it is zero, the second insertion would trigger the size check and halt further processing, resulting in a vector that either remains unchanged (non-zero) or contains a single zero (zero case).
-
No Zeros - When the input lacks zeros, the algorithm simply copies each element to
two. The size check never triggers, and the finalresizeis effectively a no-op, leaving the original ordering intact.
Performance Optimizations
The implementation incorporates several techniques that reduce runtime overhead and memory churn:
-
Early Termination - By breaking out of the loop as soon as the auxiliary vector exceeds the target size, the algorithm avoids unnecessary processing of elements that would be discarded later. This limits the number of push operations to at most
arr.size() + 1. -
Amortized Constant-Time Insertions - The use of
push_backon avectorbenefits from its exponential growth strategy, guaranteeing that each insertion runs in amortized constant time. No explicit capacity reservation is required because the early break ensures the vector never grows far beyond the needed size. -
Move Assignment - The final statement
arr = move(two);transfers ownership of the internal buffer fromtwotoarr. This eliminates a full element-wise copy, reducing both CPU cycles and temporary memory allocation. The originalarrbuffer is released automatically whentwogoes out of scope. -
In-Place Resize - The call to
two.resize(arr.size());trims excess capacity without reallocating a new buffer. The operation merely adjusts the size metadata, which is a constant-time operation. -
Range-Based Loop - The
for (auto x : arr)construct iterates directly over the elements, avoiding index calculations and providing clear intent. The loop variable is a copy of each integer, which is inexpensive for primitive types.
Collectively, these choices produce a solution that runs in linear time relative to the length of the input vector, with minimal auxiliary memory beyond the temporary container required for the transformation.
ELI5 - Simplified Explanation
Imagine you have a long row of numbered toy boxes. This code looks at your row of boxes one by one to see what is inside them. Every time the code finds a box with a zero, it adds an extra zero box right next to it. Since adding new boxes makes the row longer, it keeps track of all these boxes in a new, bigger pile. Once the new pile has enough boxes to fill the original space, it stops looking at the old row. Then it takes that new pile and shrinks it down so it fits perfectly back into the original row size, replacing the old boxes with all the new ones, including the extra zeros created along the way.
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++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | C | Rust | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Java | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| Garvit244 | Python | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| qiyuangong | Java | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
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