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.
1#include <stdio.h>
2
3void duplicateZeros(int* arr, int arrSize){
4 int i, possibleDups = 0, length = arrSize - 1;
5 for (i = 0; i <= length - possibleDups; i++) {
6 if (arr[i] == 0) {
7 if (i == length - possibleDups) {
8 arr[length] = 0;
9 length -= 1;
10 break;
11 }
12 possibleDups++;
13 }
14 }
15 int last = length - possibleDups;
16 for (i = last; i >= 0; i--) {
17 if (arr[i] == 0) {
18 arr[i + possibleDups] = 0;
19 possibleDups--;
20 arr[i + possibleDups] = 0;
21 } else {
22 arr[i + possibleDups] = arr[i];
23 }
24 }
25}
26
27int main() {
28 int arr[] = {1, 0, 2, 3, 0, 4, 5, 0};
29 int arrSize = sizeof(arr) / sizeof(arr[0]);
30 duplicateZeros(arr, arrSize);
31 for (int i = 0; i < arrSize; i++) {
32 printf("%d ", arr[i]);
33 }
34 return 0;
35}
The solution uses a two-pass method. The first pass counts the number of zeros and calculates the new length by incorporating the duplicating zeros, without exceeding the original array's bounds. The second pass migrates elements from the end to start, duplicating zeros when they appear.
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
The approach in Python mimics the manual shifting of elements that ensure correct duplication of zero in place. However, it becomes a costly strategy as elements are moved one by one.