-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-1089.cpp
More file actions
31 lines (28 loc) · 771 Bytes
/
Problem-1089.cpp
File metadata and controls
31 lines (28 loc) · 771 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Problem - 1089
// https://leetcode.com/problems/duplicate-zeros/
// O(n) time complexity and O(1) space complexity solution two pass
class Solution {
public:
void duplicateZeros(vector<int>& arr) {
int ctr = 0;
for(int i = 0; i < arr.size(); i++)
if(arr[i] == 0)
ctr++;
int i = arr.size() - 1;
int j = arr.size() + ctr - 1;
while(i >= 0 && j >= 0) {
if(arr[i] != 0) {
if(j < arr.size())
arr[j] = arr[i];
}
else {
if(j < arr.size())
arr[j] = 0;
j--;
if(j < arr.size())
arr[j] = 0;
}
--i, --j;
}
}
};