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
insertto track position for non-zero elements - Traverse the array:
- If element is non-zero → place it at
insert - Increment
insert
- If element is non-zero → place it at
- 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.
Top comments (0)