Leetcode 1089. Duplicate Zeros
Given a fixed-length integer array arr
, duplicate each occurrence of zero, shifting the remaining elements to the right. Note that elements beyond the length of the original array are not written. The modification should be done in place and there is no need to return anything from the function.
Answers:
Answer:
public class DuplicateZeros {
public void duplicateZeros(int[] arr) {
int zeros = 0;
int length = arr.length - 1;
// Count the number of zeros
for (int i = 0; i <= length - zeros; i++) {
if (arr[i] == 0) {
// Edge case for zero at the boundary
if (i == length - zeros) {
arr[length] = 0;
length--;
break;
}
zeros++;
}
}
// Copy backwards
int last = length - zeros;
for (int i = last; i >= 0; i--) {
if (arr[i] == 0) {
arr[i + zeros] = 0;
zeros--;
arr[i + zeros] = 0;
} else {
arr[i + zeros] = arr[i];
}
}
}
}
O(n)
O(1)
This solution ensures the array is modified in place with efficient traversal and in accordance with constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?