Move Zeroes — Understanding the Read & Write Pointer Pattern (C++)

Published: (February 4, 2026 at 12:27 PM EST)
2 min read
Source: Dev.to

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].

rdwrtnums[rd]ActionArray after step
000skip[0, 1, 0, 3, 12]
101swap[1, 0, 0, 3, 12]
210skip[1, 0, 0, 3, 12]
313swap[1, 3, 0, 0, 12]
4212swap[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.
Back to Blog

Related posts

Read more »

10. C# (Static Typing vs Dynamic Typing)

The Real Goal of This Lesson This lesson is not about deciding whether static typing is “better” or “worse”. The real goal is to understand when and why the C...