Skip to main content
Back to problems
#1089
Easy Algorithms

Duplicate zeros

Array Two Pointers
53.4% acceptance
Feb 25, 2026
2828
795
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. Do the above modifications to the input array in place and do not return anything.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn duplicate_zeros(arr: &mut Vec<i32>) {
    let n = arr.len();
    let zeros = arr.iter().filter(|&&x| x == 0).count();
    let mut i = n as i32 - 1;
    let mut j = (n + zeros) as i32 - 1;
    while i >= 0 {
      if arr[i as usize] == 0 {
        if j < n as i32 { arr[j as usize] = 0; }
        j -= 1;
        if j < n as i32 { arr[j as usize] = 0; }
      } else {
        if j < n as i32 { arr[j as usize] = arr[i as usize]; }
      }
      i -= 1;
      j -= 1;
    }
  }
}