DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Move Zeros

When I saw the Move Zeroes problem, it looked very easy, but it needs a small trick to solve it properly. The task is to move all the zero values in an array to the end, without changing the order of the other numbers.

For example, if the input is [0, 1, 0, 3, 12], the output should be [1, 3, 12, 0, 0]. Here, we are not sorting the array, just shifting zeroes to the end.

The idea is simple. Instead of thinking about zeroes, we focus on non-zero elements. We take a variable to track the position where the next non-zero value should be placed. Then we go through the array and place all non-zero elements in the front. After that, we fill the remaining positions with zero.

This method works in-place and does not use extra space. It is also efficient because it only scans the array.

def moveZeroes(nums):
index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[index] = nums[i]
index += 1
for i in range(index, len(nums)):
nums[i] = 0
return nums

This problem helped me understand how to handle arrays efficiently and think in a better way while solving problems.

Top comments (0)