DEV Community

Tharunya K R
Tharunya K R

Posted on

Move All Zeros to the End of an Array

Problem

Given an integer array nums, move all 0's to the end while maintaining the relative order of non-zero elements.
The operation must be done in-place without creating a new array.

Example

Input

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

Output

[1,3,12,0,0]

Input
nums = [0]

Output
[0]

Approach

Use a pointer to track the position of non-zero elements.
Traverse the array.
When a non-zero element is found, swap it with the element at the pointer.
Move the pointer forward.
This keeps all non-zero elements at the front and pushes zeros to the end.

Python Code

class Solution:
def moveZeroes(self, nums: list[int]) -> None:
last_non_zero = 0

for i in range(len(nums)):
if nums[i] != 0:
nums[last_non_zero], nums[i] = nums[i], nums[last_non_zero]
last_non_zero += 1

Output
[1, 3, 12, 0, 0]

Top comments (0)