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
-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)
~ Key Takeaways :
Uses two-pointer technique
Maintains relative order (stable)
Works in-place
Very common interview problem
Top comments (0)