When I first solved “Move Zeroes”, I didn’t struggle with the code —
I struggled with understanding why this pointer movement works.
This article explains:
- What I tried
- The exact idea behind read and write pointers
- How the algorithm works step by step
- The pattern I learned from this problem
Problem Summary
You are given an array of integers nums.Move all 0s to the end of the array without changing the relative order of non-zero elements.
Note:You must do this in-place.
Example
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Key intuition
Instead of searching for zeros,
focus on placing non-zero elements correctly.
Once non-zero values are placed in front,
zeros automatically end up at the back.
Pattern Used: Read & Write Pointers
This problem uses a two-pointer pattern:
- rd → read pointer (scans the array)
- wrt → write pointer (marks where the next non-zero should go)
My Solution (C++)
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int wrt = 0, rd = 0;
while (rd < nums.size()) {
if (nums[rd] != 0) {
swap(nums[wrt], nums[rd]);
++wrt;
}
++rd;
}
}
};
How the Code Works (Step by Step)
Let’s walk through this example:
nums = [0, 1, 0, 3, 12]
Initial State
wrt = 0
rd = 0
Step-by-step execution
| rd | wrt | nums[rd] | Action | Array |
|---|---|---|---|---|
| 0 | 0 | 0 | skip | [0,1,0,3,12] |
| 1 | 0 | 1 | swap | [1,0,0,3,12] |
| 2 | 1 | 0 | skip | [1,0,0,3,12] |
| 3 | 1 | 3 | swap | [1,3,0,0,12] |
| 4 | 2 | 12 | swap | [1,3,12,0,0] |
(Done) All non-zero elements are moved forward
(Done) Zeros naturally shift to the end
(Done) Order of non-zero elements is preserved
Why This Works
- rd always moves forward
- wrt moves only when a non-zero is found
- Each non-zero element is placed in its correct position
- Swapping avoids extra memory
Complexity Analysis
Time Complexity O(n)
Space Complexity O(1)
Extra Memory - Not used
What I Learned From This Problem
Before this, I thought . I must track zero positions. Now I understand. Just place valid elements correctly — the rest fixes itself.
This problem taught me how read/write pointers work, how to avoid unnecessary conditions, how in-place array manipulation is done efficiently
Pattern Takeaway
This same pattern appears in:
removing elements
filtering arrays
partitioning arrays
stable rearrangements
If you master this, many array problems become easier.
Final Thought
If you’re learning DSA solving it correctly comes first solving it optimally comes next. Understanding the pattern is what makes it stick
This problem helped me move one step closer to that.
Top comments (0)