imashutosh51

Duplicate Zeros

Aug 11th, 2022 (edited)
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. '''
  2. T.C O(n) two pass, space complexity O(1)
  3. Logic:
  4. We can find that what are the elments will be inside array after modification.
  5. so found the last index of element which will be present in array after first
  6. loop.
  7.  
  8. [8,4,5,0,0,0,0,7]   example of k>arr.size()
  9. one edge case, is there gonna be only one zero at end , if only one place empty at last?
  10. '''
  11.  
  12. class Solution:
  13.     def duplicateZeros(self, arr):
  14.         n = len(arr)
  15.         k = 0
  16.         i = 0
  17.        
  18.         # First loop: find last valid index to process
  19.         while i < n:
  20.             if arr[i] == 0:
  21.                 k += 2
  22.             else:
  23.                 k += 1
  24.            
  25.             if k >= n:
  26.                 break
  27.             i += 1
  28.        
  29.         j = n - 1
  30.        
  31.         # Special case when last zero fits partially
  32.         if k > n:
  33.             arr[j] = arr[i]
  34.             j -= 1
  35.             i -= 1
  36.        
  37.         # Second loop: fill from back
  38.         while i >= 0:
  39.             if arr[i] == 0:
  40.                 arr[j] = 0
  41.                 j -= 1
  42.                 arr[j] = 0
  43.                 j -= 1
  44.             else:
  45.                 arr[j] = arr[i]
  46.                 j -= 1
  47.             i -= 1
  48.  
Advertisement
Add Comment
Please, Sign In to add comment