Sponsored
Sponsored
The two-pointer technique allows us to shift elements efficiently. We use two pointers, one for the original array and one for the new modified version. The first pointer, 'i', traverses the array to count the potential size if zeros were duplicated (up to the length of the array). The second pointer, 'j', keeps track of the position for the final result.
We use these pointers to replicate zeros and copy other elements backward from the end.
Time Complexity: O(n). We go through the array twice, so it's linear with respect to the number of elements.
Space Complexity: O(1). Apart from input, we use a constant amount of extra space.
1function duplicateZeros(arr) {
2 let possibleDups = 0;
3 let length = arr.length - 1;
4 for (let left = 0; left <= length - possibleDups; ++left) {
5 if (arr[left] == 0) {
6 if (left == length - possibleDups) {
7 arr[length] = 0;
8 length -= 1;
9 break;
10 }
11 possibleDups++;
12 }
13 }
14 let last = length - possibleDups;
15 for (let i = last; i >= 0; i--) {
16 if (arr[i] == 0) {
17 arr[i + possibleDups] = 0;
18 possibleDups--;
19 arr[i + possibleDups] = 0;
20 } else {
21 arr[i + possibleDups] = arr[i];
22 }
23 }
24}
25
26let arr = [1, 0, 2, 3, 0, 4, 5, 0];
27duplicateZeros(arr);
28console.log(arr);
In JavaScript, the implementation follows the same two-pass logic, efficiently dealing with zero duplication while modifying the array in place without requiring extra space.
This approach processes the array by creating temporary space for duplicated zeros and then shifting elements accordingly. It uses a separate count to track effective elements and carefully adjusts them in-memory to avoid exceeding the bounds.
Time Complexity: O(n^2). In the worst case, each zero causes a shift of the remaining array.
Space Complexity: O(1). No extra space is used aside from input.
1
Similar JavaScript implementation performs in-place zero duplication by algorithmically shifting every element starting after each zero.