- Move Zeros
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Problem
Given an array, move all 0’s to the end while maintaining the relative order of non-zero elements.
Example:
Id="ex6"
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Approach Used: Two-Pointer Method
We use:
i → traverses the array
j → tracks position for next non-zero
Core Idea
👉 Whenever we find a non-zero element:
Swap it with position j
Move j forward
This ensures:
All non-zero elements move forward
Zeros automatically shift to the end
CODE:
class Solution:
def moveZeroes(self, nums):
j = 0 # Pointer to place the next non-zero element
for i in range(len(nums)):
if nums[i] != 0:
# Swap current element with the element at index j
nums[i], nums[j] = nums[j], nums[i]
j += 1 # Move j to the next index for placing non-zero
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
👉 This is optimal
Conclusion
The two-pointer approach:
Efficient
Clean
Preserves order
Works in one pass
👉 This is the best practical solution.
Top comments (0)