DEV Community

Jonah Blessy
Jonah Blessy

Posted on

CA 13 - Move Zeros

Problem Statement: here

PS Understanding:
In the given array, move all the 0s to the end while maintaining the order of other numbers.

Solution:
We can achieve this by bringing all the non-zero elements to the front of the array.

def moveZeroes(nums):
    j = 0

    for i in range(len(nums)):
        if nums[i] != 0:
            nums[i], nums[j] = nums[j], nums[i]
            j += 1
Enter fullscreen mode Exit fullscreen mode
  • We scan the array once while keeping pointer j that marks where the next non-zero element should go.
  • As we move through the array with another pointer i, we swap the non-zero element with the element at position j.
  • This ensures that all non-zero elements get shifted forward and j keeps moving to the next position.
  • Zeros are never directly handled. They automatically end up at the back because non-zero elements keep taking the front positions.

Top comments (0)