Fetching latest headlines…
Move Zeroes
NORTH AMERICA
πŸ‡ΊπŸ‡Έ United Statesβ€’March 22, 2026

Move Zeroes

0 views0 likes0 comments
Originally published byDev.to

Hi everyone!
Today I solved a simple but important array problem β€” moving all zeroes to the end while keeping the order of other elements same.

Problem
Given an array, move all 0s to the end while maintaining the order of non-zero elements.

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

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

My Approach

At first, I thought of creating a new array, but the problem clearly says:
Do it in-place
So I used a pointer-based approach.

Logic

  • Use a pointer insert to track position for non-zero elements
  • Traverse the array:
    • If element is non-zero β†’ place it at insert
    • Increment insert
  • After that, fill remaining positions with 0

Code (Python)
from typing import List

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

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

    for i in range(insert, len(nums)):
        nums[i] = 0

Time & Space Complexity

  • Time: O(n)
  • Space: O(1) (in-place)

Key Insight
We don’t need to swap every time β€” just overwrite non-zero elements and then fill zeros at the end.

What I Learned

  • In-place problems need careful pointer handling
  • Avoid unnecessary swaps to optimize performance
  • Simple logic can still be very efficient

Thanks for reading!
Feel free to share any other approaches or improvements.

Comments (0)

Sign in to join the discussion

Be the first to comment!