DEV Community

Mubashir
Mubashir

Posted on

Move Zeros

OVERVIEW
In this task, I worked on moving all the zeroes in an array to the end while maintaining the order of non-zero elements.

WHAT I DID
I created a function that rearranges the array such that:

  1. All non-zero elements stay in the front
  2. All zeroes move to the end
  3. The relative order remains the same

EXAMPLE
Input : nums = [0, 1, 0, 3, 12]
output : [1, 3, 12, 0, 0]

LOGIC IMPLEMENTED
To solve this problem, I used a two-pointer approach:

  1. One pointer (pos) keeps track of where to place the next non-zero element
  2. The other pointer (i) traverses the array
  3. Traverse the array
  4. If element is non-zero:
  5. Swap it with position pos
  6. Move pos forward

HOW IT WORKS

  1. First, all non-zero elements are shifted to the front
  2. While doing that, zeroes automatically move to the end
  3. The order of non-zero elements is preserved
class Solution:
    def moveZeroes(self, nums):
        pos = 0  # position for next non-zero element

        for i in range(len(nums)):
            if nums[i] != 0:
                nums[pos], nums[i] = nums[i], nums[pos]
                pos += 1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)