Skip to lesson

Read and write pointers

Deleting an element from the middle of a fixed-size array by shifting everything after it one step left takes O(n) time per deletion — and O(n²) time when repeated across the array. Same-direction read and write pointers compact the elements you want to keep in a single O(n) pass with O(1) extra space.

Remove a given value and keep the original order

Read and write pointers is a two-pointer pattern where one index reads every element and the other writes only the elements to keep, changing the array in place.

Use two index variables: read inspects every element, and write marks where the next kept element goes.

  1. Set int write = 0;.
  2. Loop for (int read = 0; read < nums.length; read++).
  3. If nums[read] should be kept, assign nums[write] = nums[read] and increment write++.
  4. Return write as the count of kept elements in nums[0 .. write - 1].

Example 1 · Removing all instances of a value in place

RemoveElementDemo.javaJava
import java.util.Arrays;
public class RemoveElementDemo {    public static int removeElement(int[] nums, int val) {        int write = 0;        for (int read = 0; read < nums.length; read++) {            if (nums[read] != val) {                nums[write++] = nums[read];            }        }        return write;    }
    public static void main(String[] args) {        int[] nums = {0, 1, 2, 2, 3, 0, 4, 2};        int newLen = removeElement(nums, 2);        System.out.println("New length: " + newLen);        System.out.println("Kept prefix: " + Arrays.toString(Arrays.copyOf(nums, newLen)));    }}
Output
New length: 5
Kept prefix: [0, 1, 3, 0, 4]

What this code does

  • All three 2s are skipped by write, while [0, 1, 3, 0, 4] are compacted into nums[0..4] in their original order.
  • Elements at nums[newLen .. nums.length - 1] are outside the logical array and ignored by callers.

Think of the array as having two regions during the scan:

  • nums[0 .. write - 1]: the clean, compacted prefix of elements we have already kept.
  • read: the current index being inspected (0 to n - 1).

Because write only increments when an element is kept, write <= read is always true, so writing to nums[write] never overwrites an uninspected element! Moreover, because read scans strictly left to right, the kept elements stay in their exact original relative order. To remove all occurrences of val (Remove Element), start write = 0 and loop read from 0 to n - 1. Whenever nums[read] != val, copy nums[write++] = nums[read]. At the end, write is the new logical length of the array.

Remove duplicates in place from a sorted array

In a sorted array, all duplicate copies of any number sit side by side in a contiguous block (for example, [0, 0, 1, 1, 1, 2, 2, 3]).

Example 2 · Removing duplicates in place (at most 1 copy and at most 2 copies)

RemoveDuplicatesDemo.javaJava
import java.util.Arrays;
public class RemoveDuplicatesDemo {    public static int removeDuplicatesOnce(int[] nums) {        if (nums.length == 0) return 0;        int write = 1;        for (int read = 1; read < nums.length; read++) {            if (nums[read] != nums[write - 1]) {                nums[write++] = nums[read];            }        }        return write;    }
    public static int removeDuplicatesAtMostK(int[] nums, int k) {        if (nums.length <= k) return nums.length;        int write = k;        for (int read = k; read < nums.length; read++) {            if (nums[read] != nums[write - k]) {                nums[write++] = nums[read];            }        }        return write;    }
    public static void main(String[] args) {        int[] a = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};        int len1 = removeDuplicatesOnce(a);        System.out.println("At most 1 copy (len=" + len1 + "): " + Arrays.toString(Arrays.copyOf(a, len1)));
        int[] b = {1, 1, 1, 2, 2, 3};        int len2 = removeDuplicatesAtMostK(b, 2);        System.out.println("At most 2 copies (len=" + len2 + "): " + Arrays.toString(Arrays.copyOf(b, len2)));    }}
Output
At most 1 copy (len=5): [0, 1, 2, 3, 4]
At most 2 copies (len=5): [1, 1, 2, 2, 3]

What this code does

  • Comparing nums[read] against nums[write - 1] (or nums[write - k]) always checks the compacted prefix, which never gets corrupted even as nums is overwritten in place.
  • The generalised nums[read] != nums[write - k] rule works because if nums[read] == nums[write - k], then the last k kept elements are already equal to nums[read].

The very first element nums[0] is always unique, so we can start write = 1 and scan read from 1 to n - 1.

How do we know whether nums[read] is a brand-new value? Compare it against the last kept unique element at nums[write - 1]! Whenever nums[read] != nums[write - 1], write nums[write++] = nums[read]. This same pattern generalizes to at most k duplicates (Remove Duplicates from Sorted Array II): the first k elements are always kept (write = k), and for read >= k, we keep nums[read] whenever nums[read] != nums[write - k].

  • At most 1 copy: start write = 1, keep nums[read] when nums[read] != nums[write - 1].
  • At most k copies: start write = k, keep nums[read] when nums[read] != nums[write - k].
  • Empty array guard: if nums.length <= k, simply return nums.length.

Move zeros to the end

Given an array like [0, 1, 0, 3, 12], moving all 0s to the end while keeping [1, 3, 12] in order (Move Zeroes) can be done in two ways with read and write.

Example 3 · Moving zeros to the end while keeping non-zero order

MoveZerosDemo.javaJava
import java.util.Arrays;
public class MoveZerosDemo {    public static void moveZeroes(int[] nums) {        int write = 0;        for (int read = 0; read < nums.length; read++) {            if (nums[read] != 0) {                if (read != write) {                    int temp = nums[write];                    nums[write] = nums[read];                    nums[read] = temp;                }                write++;            }        }    }
    public static void main(String[] args) {        int[] nums = {0, 1, 0, 3, 12};        moveZeroes(nums);        System.out.println("After moveZeroes: " + Arrays.toString(nums));    }}
Output
After moveZeroes: [1, 3, 12, 0, 0]

What this code does

  • At read = 0, nums[0] is 0, so write stays at 0.
  • At read = 1, nums[1] = 1 swaps with nums[0], giving [1, 0, 0, 3, 12] and write = 1. The invariant is that every index between write and read - 1 holds 0.
  1. Compact then fill: Copy every non-zero nums[read] to nums[write++], and then run a short while (write < nums.length) nums[write++] = 0; loop to zero out the tail.
  2. Single-pass swap: Whenever nums[read] != 0, swap nums[write] and nums[read] and increment write++. Any 0s sitting between write and read get pushed rightward automatically while non-zero elements stay in their exact original order.
In both approaches, every element is read once and written at most once, taking O(n) time and O(1) space.

Next step

Check your understanding

10 quick questions