Read and write pointers
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
- Set
int write = 0;. - Loop
for (int read = 0; read < nums.length; read++). - If
nums[read]should be kept, assignnums[write] = nums[read]and incrementwrite++. - Return
writeas the count of kept elements innums[0 .. write - 1].
Example 1 · Removing all instances of a value in place
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))); }}New length: 5 Kept prefix: [0, 1, 3, 0, 4]
What this code does
- All three
2s are skipped bywrite, while[0, 1, 3, 0, 4]are compacted intonums[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 (0ton - 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)
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))); }}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]againstnums[write - 1](ornums[write - k]) always checks the compacted prefix, which never gets corrupted even asnumsis overwritten in place. - The generalised
nums[read] != nums[write - k]rule works because ifnums[read] == nums[write - k], then the last k kept elements are already equal tonums[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, keepnums[read]whennums[read] != nums[write - 1]. - At most k copies: start
write = k, keepnums[read]whennums[read] != nums[write - k]. - Empty array guard: if
nums.length <= k, simply returnnums.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
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)); }}After moveZeroes: [1, 3, 12, 0, 0]
What this code does
- At
read = 0,nums[0]is0, sowritestays at0. - At
read = 1,nums[1] = 1swaps withnums[0], giving[1, 0, 0, 3, 12]andwrite = 1. The invariant is that every index betweenwriteandread - 1holds0.
- Compact then fill: Copy every non-zero
nums[read]tonums[write++], and then run a shortwhile (write < nums.length) nums[write++] = 0;loop to zero out the tail. - Single-pass swap: Whenever
nums[read] != 0, swapnums[write]andnums[read]and incrementwrite++. Any0s sitting betweenwriteandreadget pushed rightward automatically while non-zero elements stay in their exact original order.
Next step
Check your understanding
10 quick questions