DEV Community

Cover image for Move Zeros
Abirami Prabhakar
Abirami Prabhakar

Posted on

Move Zeros

The move zeroes question is a leetcode question that works on rearranging the elements in an array such that all the zeroes are moved to the end while maintaining the relative order of the non-zero elements

example
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]_

How does the array change?

the array changes when we move all non-zero elements to the front and push zeroes to the end

let the given array be

arr = [0, 1, 0, 3, 12]
Enter fullscreen mode Exit fullscreen mode

the output should be

[1,3,12,0,0]
Enter fullscreen mode Exit fullscreen mode

so when the question is to move all zeroes to the end, we make sure that the order of 1, 3, 12 remains the same

Approach to solve the question

Move all non-zero elements to the front → remaining positions will automatically be zeroes

arr = [0, 1, 0, 3, 12]

Step 1 : to place non-zero elements when we traverse left to right

0 → skip
1 → place at front
0 → skip
3 → place next
12 → place next

so the array becomes

[1,3,12,,]

step 2: fill the remaining positions with zeroes

[1,3,12,0,0]

Algorithm

def moveZeroes(nums):
pos = 0

    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)