Move Zeroes — Understanding the Read & Write Pointer Pattern (C++)
Source: Dev.to
Problem Summary
You are given an array of integers nums. Move all 0s to the end of the array in‑place while preserving the relative order of the non‑zero elements.
Example
- Input:
[0, 1, 0, 3, 12] - Output:
[1, 3, 12, 0, 0]
Key Intuition
The problem can be solved with a two‑pointer (read/write) pattern:
rd(read pointer) – scans the array from left to right.wrt(write pointer) – marks the position where the next non‑zero element should be placed.
When nums[rd] is non‑zero, swap it with nums[wrt] and advance wrt.
rd always moves forward; wrt only moves when a non‑zero is found.
All zeros naturally shift to the end.
Solution (C++)
class Solution {
public:
void moveZeroes(vector& nums) {
int wrt = 0, rd = 0;
while (rd < nums.size()) {
if (nums[rd] != 0) {
swap(nums[wrt], nums[rd]);
++wrt;
}
++rd;
}
}
};
Walkthrough Example
Consider nums = [0, 1, 0, 3, 12].
| rd | wrt | nums[rd] | Action | Array after step |
|---|---|---|---|---|
| 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] |
After the loop finishes:
- All non‑zero elements are at the front in their original order.
- Zeros have been pushed to the end.
Complexity Analysis
- Time:
O(n)– each element is inspected once. - Space:
O(1)– only two integer pointers are used.
Takeaways
- The read/write pointer pattern is a powerful tool for in‑place array manipulation.
- By focusing on placing valid elements correctly, the “invalid” elements (zeros) automatically end up where they belong.
- This pattern appears in many other array problems, such as removing elements or compacting data.
- Mastering it simplifies a large class of DSA problems and leads to cleaner, more efficient code.