Let's make this one less mysterious. For 1089. Duplicate Zeros, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are duplicateZeros.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The code keeps the moving pieces local, so the main idea stays visible.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(N), space: O(1)
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 40 ms, faster than 27.67% of C++ online submissions for Duplicate Zeros.
02//Memory Usage: 9.5 MB, less than 100.00% of C++ online submissions for Duplicate Zeros.
03
04class Solution {
05public:
06 void duplicateZeros(vector<int>& arr) {
07 int n = arr.size();
08
09 for(int i = n-1; i >= 0; i--){
10 if(arr[i] == 0){
11 arr.insert(arr.begin() + i, 0);
12 }
13 }
14
15 arr.resize(n);
16 }
17};
18
19//official sol
20//time: O(N), space: O(1)
21//Runtime: 16 ms, faster than 98.61% of C++ online submissions for Duplicate Zeros.
22//Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Duplicate Zeros.
23
24class Solution {
25public:
26 void duplicateZeros(vector<int>& arr) {
27 int possibleDups = 0;
28 int n = arr.size();
29
30 for(int left = 0; left + possibleDups < n; left++){
31 if(arr[left] == 0){
32 if(left + possibleDups == n - 1){
33 //set the last element to 0
34 //and decrease the effective length by 1
35 arr[n-1] = 0;
36 n -= 1;
37 break;
38 }
39 //zero's count
40 possibleDups++;
41 }
42 }
43
44 int last = n - 1 - possibleDups;
45 //fill from the end
46 for(int i = last; i >= 0; i--){
47 if(arr[i] == 0){
48 //0 take 2 places
49 arr[i + possibleDups] = 0;
50 arr[i + possibleDups - 1] = 0;
51 possibleDups--;
52 }else{
53 arr[i + possibleDups] = arr[i];
54 }
55 }
56 }
57};
Cost