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
5h ago
Officer Leaks Location of French Aircraft Carrier With Strava Run
5h ago
Microsoft Says It Is Fixing Windows 11
5h ago
NASA's Hubble Unexpectedly Catches Comet Breaking Up
5h ago
Intel, NVIDIA, AMD GPU Drivers Finally Play Nice With ReactOS
5h ago