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.
United States
NORTH AMERICA
Related News
Jeff Bezos Seeking $100 Billion to Buy Manufacturing Companies, 'Transform' Them With AI
9h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
Can Private Space Companies Replace the ISS Before 2030?
9h ago
Juicier Steaks Soon? The UK Approves Testing of Gene-Edited Cow Feed
9h ago
White House Unveils National AI Policy Framework To Limit State Power
9h ago