Problem 1089

Abstract / Summary

Move zeros forward to duplicate them and shift remaining elements to the right in an array of fixed size.

Note

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

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);
    }
};
18 lines | 379 bytes | submitted August 9, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 53% (900k+ 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 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 arr contains no elements, the range-based loop executes zero times. The auxiliary vector remains empty, resize is a no-op, and the move assignment leaves arr unchanged.

  • All Zeros - If every element of arr is 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 final resize is 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_back on a vector benefits 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 from two to arr. This eliminates a full element-wise copy, reducing both CPU cycles and temporary memory allocation. The original arr buffer is released automatically when two goes 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.

written by openai gpt

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.

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 | μ = 6.19 | σ = 1.47

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++ 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
35 links | 21 authors | 10 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

9 easy 2 medium 16 hard
28 solutions   August 9, 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