DEV Community

Ashiq Omar
Ashiq Omar

Posted on

Move Zeros

In this task, I worked on rearranging an array so that all the zeroes are moved to the end, while keeping the order of the non-zero elements the same.

What I Did
I created a function called moveZeroes that takes an array and shifts all zero values to the end without changing the order of the other elements.

For example:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
How I Solved It
To solve this problem, I used a variable called insert_pos to keep track of where the next non-zero element should go.
First, I went through the array:
If the element is not zero, I placed it at the insert_pos and moved the position forward
After placing all non-zero elements, I filled the remaining positions in the array with zeroes.

CODE:

def moveZeroes(nums):
    insert_pos = 0
    for num in nums:
        if num != 0:
            nums[insert_pos] = num
            insert_pos += 1
    while insert_pos < len(nums):
        nums[insert_pos] = 0
        insert_pos += 1

nums = [0, 1, 0, 3, 12]
print("Before:", nums)
moveZeroes(nums)
print("After:", nums)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)