Move Zeroes
Problem Statement
Given an array, move all 0’s to the end while maintaining the relative order of non-zero elements.
The operation must be done in-place.
Example
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Approach 1: Extra Array (Simple but Not In-place)
Idea
Store all non-zero elements
Add zeros at the end
Replace original array
Code
nums = [0,1,0,3,12]
temp = [i for i in nums if i != 0]
zeros = [0] * (len(nums) - len(temp))
nums[:] = temp + zeros
print(nums)
Complexity
Time: O(n)
Space: O(n)
But the problem requires in-place, so we need a better method.
Approach 2: Two Pointer Method (Best Solution)
Idea
Use a pointer j to place non-zero elements
Traverse array with i
If element is non-zero → swap with position j
Increment j
This keeps order and moves zeros automatically to end.
Code
nums = [0,1,0,3,12]
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
print(nums)
Complexity
Type Complexity
Time O(n)
Space O(1)
This is the optimal solution.
Top comments (0)