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: …


This content originally appeared on DEV Community and was authored by Abirami Prabhakar

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]

the output should be

[1,3,12,0,0]

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 


This content originally appeared on DEV Community and was authored by Abirami Prabhakar


Print Share Comment Cite Upload Translate Updates
APA

Abirami Prabhakar | Sciencx (2026-03-20T18:50:05+00:00) Move Zeros. Retrieved from https://www.scien.cx/2026/03/20/move-zeros/

MLA
" » Move Zeros." Abirami Prabhakar | Sciencx - Friday March 20, 2026, https://www.scien.cx/2026/03/20/move-zeros/
HARVARD
Abirami Prabhakar | Sciencx Friday March 20, 2026 » Move Zeros., viewed ,<https://www.scien.cx/2026/03/20/move-zeros/>
VANCOUVER
Abirami Prabhakar | Sciencx - » Move Zeros. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2026/03/20/move-zeros/
CHICAGO
" » Move Zeros." Abirami Prabhakar | Sciencx - Accessed . https://www.scien.cx/2026/03/20/move-zeros/
IEEE
" » Move Zeros." Abirami Prabhakar | Sciencx [Online]. Available: https://www.scien.cx/2026/03/20/move-zeros/. [Accessed: ]
rf:citation
» Move Zeros | Abirami Prabhakar | Sciencx | https://www.scien.cx/2026/03/20/move-zeros/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.