DEV Community

Samantha Vincent
Samantha Vincent

Posted on

Move Zeros

Move Zeroes

Problem

You’re given an array and need to move all 0s to the end, while keeping the order of the non-zero elements the same.

The catch is that it has to be done in-place.


Strategy

At first, it feels like you need to shift elements every time you see a zero.

But that quickly gets messy.

Instead, I focused on the non-zero elements:

  • Keep a position for where the next non-zero should go
  • Traverse the array once
  • Every time I see a non-zero, move it to that position

So instead of pushing zeros back, I’m just pulling non-zero elements forward.


Code

class Solution:
    def moveZeroes(self, nums):
        j = 0

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

Key Lines Explained

  • j = 0
    This keeps track of where the next non-zero element should be placed.

  • if nums[i] != 0:
    We only act when we find a non-zero value.

  • nums[j], nums[i] = nums[i], nums[j]
    This moves the non-zero element forward without losing order.

  • j += 1
    Move to the next position after placing a non-zero.


Why This Works

All non-zero elements are moved forward in the same order they appear.

Zeros are never explicitly moved — they just get pushed to the end as a result of the swaps.


Complexity

  • Time: O(n)
  • Space: O(1)

Final Note

This problem looks like it’s about zeros, but it’s actually about placing non-zero elements correctly.

Once that perspective shifts, the solution becomes straightforward.

Top comments (0)