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.
1using System;
2
3class Solution {
4 public void DuplicateZeros(int[] arr) {
5 int possibleDups = 0;
6 int length = arr.Length - 1;
7 for (int left = 0; left <= length - possibleDups; ++left) {
8 if (arr[left] == 0) {
9 if (left == length - possibleDups) {
10 arr[length] = 0;
11 length -= 1;
12 break;
13 }
14 possibleDups++;
15 }
16 }
17 int last = length - possibleDups;
18 for (int i = last; i >= 0; i--) {
19 if (arr[i] == 0) {
20 arr[i + possibleDups] = 0;
21 possibleDups--;
22 arr[i + possibleDups] = 0;
23 } else {
24 arr[i + possibleDups] = arr[i];
25 }
26 }
27 }
28
29 static void Main(string[] args) {
30 int[] arr = {1, 0, 2, 3, 0, 4, 5, 0};
31 Solution sol = new Solution();
32 sol.DuplicateZeros(arr);
33 Console.WriteLine(string.Join(" ", arr));
34 }
35}
36
The implementation in C# uses the same two-pointer mechanism and logic as in Java and C++, providing efficient zero duplication within the input constraints.
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
class Solution {
public void DuplicateZeros(int[] arr) {
int idx = 0;
int n = arr.Length;
while (idx < n) {
if (arr[idx] == 0) {
for (int j = n - 1; j > idx; j--) {
arr[j] = arr[j - 1];
}
idx++;
}
idx++;
}
}
static void Main(string[] args) {
int[] arr = {1, 0, 2, 3, 0, 4, 5, 0};
Solution sol = new Solution();
sol.DuplicateZeros(arr);
Console.WriteLine(string.Join(" ", arr));
}
}
C# solution follows a manual element shift whenever a zero is encountered similar to other languages, ensuring the operation is done in place while respecting array bounds.