-
Notifications
You must be signed in to change notification settings - Fork 0
/
duplicateZeros.py
52 lines (37 loc) · 2.1 KB
/
duplicateZeros.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Duplicate Zeros
# Given a fixed length array arr of integers, 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, do not return anything from your function.
# Example 1:
# Input: [1,0,2,3,0,4,5,0]
# Output: null
# Explanation: After calling your function, the input array is modified to: [1,0,0,2,3,0,0,4]
# Example 2:
# Input: [1,2,3]
# Output: null
# Explanation: After calling your function, the input array is modified to: [1,2,3]
# Note:
# 1 <= arr.length <= 10000
# 0 <= arr[i] <= 9
# Hide Hint #1
# This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything.
# Hide Hint #2
# A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory.
# Hide Hint #3
# The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that?
# Hide Hint #4
# If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
## The main point to focus on in this question and solution is the fact that the length of the output array is to be the same as the input array.
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
l = len(arr)
i = 0
while i < l-1:
if arr[i] == 0:
arr.pop()
arr.insert(i+1,0)
i += 1
i+=1