DEV Community

Santhosh V
Santhosh V

Posted on

CA 13 - Move Zeros

Problem

Given an integer array nums, the task is to move all 0's to the end while maintaining the relative order of the non-zero elements.

The operation must be done in-place without making a copy of the array.

Output

Example 1
Output: [1, 3, 12, 0, 0]
Example 2
Output: [0]
Enter fullscreen mode Exit fullscreen mode

My Approach

To solve this problem, I used the two-pointer technique.

I maintain a pointer j to track the position where the next non-zero element should be placed.

I iterate through the array:

If the current element is non-zero, I swap it with the element at index j
Then I increment j

This ensures that all non-zero elements are moved to the front in their original order, and all zeroes are pushed to the end.

This approach is efficient because:

It requires only one traversal
It uses constant extra space
Code

def move_zeroes(nums):
    j = 0
    for i in range(len(nums)):
        if nums[i] != 0:
            nums[j], nums[i] = nums[i], nums[j]
            j += 1
    return nums
Enter fullscreen mode Exit fullscreen mode

Top comments (0)