#1089
Duplicate Zeros
EasyArrayTwo PointersTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a two-pass approach to count zeros and adjust the array in place without needing extra space. This method ensures we only traverse the array a couple of times, making it efficient.
⚙️
Algorithm
3 steps- 1Step 1: Count the number of zeros in the array while determining the effective length of the new array.
- 2Step 2: Iterate backwards through the array, placing elements in their new positions based on the counted zeros.
- 3Step 3: If a zero is encountered, place two zeros in the new position.
solution.py13 lines
1# Full working Python code
2
3def duplicateZeros(arr):
4 n = len(arr)
5 zeros = arr.count(0)
6 for i in range(n - 1, -1, -1):
7 if i + zeros < n:
8 arr[i + zeros] = arr[i]
9 if arr[i] == 0:
10 zeros -= 1
11 if i + zeros < n:
12 arr[i + zeros] = 0
13ℹ
Complexity note: The time complexity is O(n) because we only traverse the array a couple of times. The space complexity is O(1) since we are modifying the array in place without using extra space.
- 1Understanding in-place operations is crucial.
- 2Counting elements before modifying helps avoid overwriting data.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.