Two Pointers
Easy
Move Zeroes
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
10 min read
Solve on LeetCodeExamples
Input:nums = [0,1,0,3,12]
Output:[1,3,12,0,0]
Explain:
Non-zero elements are 1, 3, 12. They stay in that order. The 0s go to the end.
Input:nums = [0]
Output:[0]
Problem Understanding
We need to push all 0s to the right side of the array.
Constraints:
- In-place: You cannot copy the valid numbers to a new array. You must do it inside
nums. - Relative Order: If
1comes before3originally, it must stay that way. - Minimize Operations: Ideally O(n) time.
Algorithm Strategy
We can use the Two Pointers technique to partition the array.
leftpointer: Tracks the position where the next non-zero element should go.rightpointer: Scans the array to find non-zero elements.
Logic:
- Iterate through the array with
right. - If
nums[right]is non-zero, we want to place it atnums[left]. - Swap
nums[left]andnums[right]. Thenleft++. - If
nums[right]is zero, just continue scanning (right++).
Interactive Visualization
Step 1 / 5
L
R
0
01
10
23
312
4Start: L=0, R=0.
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run: nums = [0, 1, 0, 3, 12]
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
