Move All Zeros to the End (In-Place & Stable)
Rearranging arrays efficiently is a key skill in coding interviews.
Letβs solve a classic problem: moving all zeros to the end while maintaining order π
π Problem Statement
Given an integer array nums, move all 0s to the end of the array.
β οΈ Constraints:
Maintain the relative order of non-zero elements
Perform the operation in-place
Do not create a copy of the array
π§ͺ Examples
Example 1
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Example 2
Input: [0]
Output: [0]
π‘ Optimal Approach: Two-Pointer Technique
We use a two-pointer approach to solve this efficiently.
i β scans the array
j β tracks position to place next non-zero element
π§ Core Idea
π Move all non-zero elements forward
π Fill remaining positions with 0s
This ensures:
Order is preserved β
No extra space is used β
π Algorithm Steps
Initialize j = 0
Traverse array using i
If nums[i] != 0:
Swap nums[i] with nums[j]
Increment j
Continue till end
π» Python Implementation
def move_zeros(nums):
j = 0 # position for next non-zero
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[j] = nums[j], nums[i]
j += 1
Example usage
nums = [0, 1, 0, 3, 12]
move_zeros(nums)
print(nums)
π§Ύ Output
[1, 3, 12, 0, 0]
π Dry Run (Quick Insight)
For:
[0, 1, 0, 3, 12]
Move 1 β front
Move 3 β next
Move 12 β next
Remaining filled with 0s
β‘ Complexity Analysis
Metric Value
Time Complexity O(n)
Space Complexity O(1)
π― Key Takeaways
Uses two-pointer technique π₯
Maintains relative order (stable) β
Works in-place β
Very common interview problem π‘
π Conclusion
This problem highlights how a simple pointer strategy can lead to an optimal solution without extra space.
Master this pattern β itβs widely used in array manipulation problems π
Top comments (0)