Problem Statement
Given an integer array nums, move all 0s to the end of the array while maintaining the relative order of the non-zero elements.
Important Conditions:
The operation must be done in-place
Do not create a copy of the array
Example 1
Input:
nums = [0,1,0,3,12]
Output:
[1,3,12,0,0]
Explanation:
Non-zero elements → 1, 3, 12 (order preserved)
Zeros moved to the end
Example 2
Input:
nums = [0]
Output:
[0]
Constraints
1 <= nums.length <= 10^4
-2^31 <= nums[i] <= 2^31 - 1
Efficient Approach – Two Pointer Method
To maintain order and minimize operations, we use a two-pointer technique.
Key Idea
Maintain a pointer index for the position where the next non-zero element should go.
Traverse the array.
Whenever we find a non-zero element:
Swap it with nums[index]
Increment index
This ensures:
All non-zero elements move forward
All zeros automatically move to the end
Why This Minimizes Operations
Each element is moved at most once.
We only swap when necessary.
Time Complexity is O(n)
Space Complexity is O(1)
Step-by-Step Logic
Initialize index = 0
Traverse the array:
If nums[i] != 0
Swap nums[i] with nums[index]
Increment index
End of loop → all zeros are automatically at the end
Implementation (Python)
class Solution:
def moveZeroes(self, nums):
index = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[index], nums[i] = nums[i], nums[index]
index += 1
Dry Run Example
For:
[0,1,0,3,12]
Step-by-step:
i = 0 → 0 → ignore
i = 1 → 1 → swap with index 0 → [1,0,0,3,12]
i = 2 → 0 → ignore
i = 3 → 3 → swap with index 1 → [1,3,0,0,12]
i = 4 → 12 → swap with index 2 → [1,3,12,0,0]
Final result:
[1,3,12,0,0]
Top comments (0)