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 <vector>
2#include <iostream>
3
4void duplicateZeros(std::vector<int>& arr) {
5 int possibleDups = 0;
6 int length = arr.size() - 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
29int main() {
30 std::vector<int> arr = {1, 0, 2, 3, 0, 4, 5, 0};
31 duplicateZeros(arr);
32 for (int num : arr) {
33 std::cout << num << " ";
34 }
35 return 0;
36}
Similar to C, the C++ solution uses two iterations over the vector, one to calculate the number of effective elements with extended length for duplicates and another to shift elements to their new positions from the back.
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 Java realizes in-place shifting of elements for each zero it encounters without requiring extra space as it dynamically adjusts elements to fit the transformation.