In-place Move Zeros to End of List in Python


Suppose we have a list of numbers nums, we have to put all the zeros to the end of the list by updating the list in-place. And the relative ordering of other elements should not be changed. We have to try to solve this in O(1) additional space.

So, if the input is like [2,0,1,4,0,5,6,4,0,1,7], then the output will be [2, 1, 4, 5, 6, 4, 1, 7, 0, 0, 0]

To solve this, we will follow these steps −

  • if size of L is same as 0, then
    • return a blank list
  • k := 0
  • for i in range 0 to size of L, do
    • if L[i] is not same as 0, then
      • L[k] := L[i]
      • k := k + 1
  • for j in range k to size of L, do
    • L[j] := 0
  • return L

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, L):
      if len(L) == 0:
         return []
         k = 0
         for i in range(len(L)):
            if L[i] != 0:
               L[k] = L[i]
               k+=1
         for j in range(k,len(L)):
            L[j] = 0
         return L
ob = Solution()
L = [2,0,1,4,0,5,6,4,0,1,7]
print(ob.solve(L))

Input

[2,0,1,4,0,5,6,4,0,1,7]

Output

[2, 1, 4, 5, 6, 4, 1, 7, 0, 0, 0]

Updated on: 23-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements