Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- T.C O(n) two pass, space complexity O(1)
- Logic:
- We can find that what are the elments will be inside array after modification.
- so found the last index of element which will be present in array after first
- loop.
- [8,4,5,0,0,0,0,7] example of k>arr.size()
- one edge case, is there gonna be only one zero at end , if only one place empty at last?
- '''
- class Solution:
- def duplicateZeros(self, arr):
- n = len(arr)
- k = 0
- i = 0
- # First loop: find last valid index to process
- while i < n:
- if arr[i] == 0:
- k += 2
- else:
- k += 1
- if k >= n:
- break
- i += 1
- j = n - 1
- # Special case when last zero fits partially
- if k > n:
- arr[j] = arr[i]
- j -= 1
- i -= 1
- # Second loop: fill from back
- while i >= 0:
- if arr[i] == 0:
- arr[j] = 0
- j -= 1
- arr[j] = 0
- j -= 1
- else:
- arr[j] = arr[i]
- j -= 1
- i -= 1
Advertisement
Add Comment
Please, Sign In to add comment