Problem Statement
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note: You must do this in-place without making a copy of the array.
Examples:
Input: nums = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Input: nums = [0]
Output: [0]
My Goal
For this problem, my goal was to:
Maintain the order of non-zero elements
Move all zeros efficiently to the end
Solve the problem in-place (no extra array)
Keep the solution simple and optimal
Solution
I used a two-pointer approach to solve this efficiently.
Idea:
Use one pointer i to place non-zero elements
Traverse array using another pointer j
When a non-zero element is found:
Swap it with position i
Increment i
This ensures all non-zero elements come forward, and zeros automatically move to the end.
Solution Code (Python)
a = [0, 1, 0, 3, 12]
i = 0
for j in range(len(a)):
if a[j] != 0:
a[i], a[j] = a[j], a[i]
i += 1
print(a)
Explanation
i keeps track of where the next non-zero element should go
j scans the array
When a non-zero element is found:
Swap it to position i
Move i forward
By the end, all zeros shift to the right
Top comments (0)