DEV Community

Sandhya Steffy M
Sandhya Steffy M

Posted on

Move Zeroes to End of Array

Problem Statement:
Given an integer array, move all 0’s to the end while maintaining the relative order of non-zero elements. The operation must be done in-place.

Example:
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]

Approach:
We use a pointer to track the position where the next non-zero element should be placed. First, we move all non-zero elements to the front. Then, we fill the remaining positions with zero.

Code:

def moveZeroes(nums):
pos = 0

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

for i in range(pos, len(nums)):
    nums[i] = 0
Enter fullscreen mode Exit fullscreen mode

Explanation:
The algorithm maintains the order of non-zero elements while shifting all zeros to the end. It works in-place and does not require extra memory.

Time Complexity:
O(n), single traversal

Space Complexity:
O(1), no extra space

Top comments (0)