LeetCode 1089: Duplicate Zeros Solution

Master LeetCode problem 1089 (Duplicate Zeros), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1089. Duplicate Zeros

Problem Explanation

Explanation:

To solve this problem, we need to iterate through the array and duplicate each zero we encounter by shifting the elements to the right. We need to be careful not to write elements beyond the length of the original array.

  1. Iterate through the array from left to right.
  2. Whenever we encounter a zero, shift the elements to the right to make space for the duplicate zero.
  3. Continue this process until we reach the end of the array.

Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(1) :

Solution Code

class Solution {
    public void duplicateZeros(int[] arr) {
        int zeros = 0;
        for (int num : arr) {
            if (num == 0) {
                zeros++;
            }
        }
        
        int len = arr.length;
        int i = len + zeros - 1;
        for (int j = len - 1; j >= 0; j--) {
            if (i < len) {
                arr[i] = arr[j];
            }
            if (arr[j] == 0) {
                i--;
                if (i < len) {
                    arr[i] = 0;
                }
            }
            i--;
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1089 (Duplicate Zeros)?

This page provides optimized solutions for LeetCode problem 1089 (Duplicate Zeros) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1089 (Duplicate Zeros)?

The time complexity for LeetCode 1089 (Duplicate Zeros) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1089 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1089 in Java, C++, or Python.

Back to LeetCode Solutions