DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

MOVE ZEROES

*How I Understood Moving Zeroes to the End (LeetCode 283)
*

When I first saw this problem, it looked simple but also tricky because it asks to move all zeros to the end while keeping the relative order of non-zero elements.
After breaking it down, I realized the solution is simple if you focus on tracking the position for non-zero elements.

Problem
Given an array, move all zeros to the end in-place, while maintaining the relative order of non-zero elements.
Example:
Python
nums = [0, 1, 0, 3, 12]
Expected output:
Python
[1, 3, 12, 0, 0]
Notice that the order of non-zero numbers stays the same, and all zeros are at the end.

** What I Noticed**
Instead of trying to swap zeros one by one with all other elements, I focused on tracking where the next non-zero element should go.
This led to a single-pass, in-place solution.

What Helped Me
Using a pointer last_non_zero made the logic very clear:
Keep track of the position for the next non-zero element
Iterate through the array:
If the current element is non-zero, swap it with the element at last_non_zero
Move last_non_zero forward
Continue until the end of the array
This way, all non-zero elements are moved to the front in order, and zeros automatically end up at the back.

Code (Python)
Python
from typing import List

class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Move all zeros to the end of the array in-place.
"""
# Pointer for the next position of a non-zero element
last_non_zero = 0

    for current in range(len(nums)):
        if nums[current] != 0:
            # Swap current non-zero with the last non-zero position
            nums[last_non_zero], nums[current] = nums[current], nums[last_non_zero]
            last_non_zero += 1
Enter fullscreen mode Exit fullscreen mode

Example Usage
Python
nums = [0, 1, 0, 3, 12]
solution = Solution()
solution.moveZeroes(nums)
print(nums)
Output:
Plain text
[1, 3, 12, 0, 0]

Complexity
Time: O(n) — iterate through the array once
Space: O(1) — in-place, no extra space

What I Learned
This problem is less about complicated logic and more about thinking clearly:
Use a pointer to track the position for non-zero elements
Swap only when needed
Process the array in a single pass
It’s a classic example of two-pointer technique in arrays.

** Final Thought**
At first, moving zeros seemed straightforward but tricky because of the order constraint.
Once I realized:
“Where should the next non-zero element go?”
…it became easy to implement.
This shows that clarity and careful pointer tracking beats brute force.

Top comments (0)