Same-Direction Two Pointers: Removing Duplicates and In-Place Partitioning
Learn same direction two pointers with read and write indexes: remove duplicates, move zeroes, merge sorted arrays from the end, in tested Python and Java.

A loop calls nums.remove(0) every time it sees a zero. On a list of 100,000 numbers that is half zeros, each removal shifts every later element one slot left. The code is short and readable, and it does billions of element moves. In Java the same idea inside a for-each loop over an ArrayList throws ConcurrentModificationException instead.
Same direction two pointers is the pattern that fixes this. One index, read, visits every element once. A second index, write, trails behind it and points at the next free slot in the output. When read finds an element worth keeping, you copy it to write and advance write. Nothing is ever deleted during the pass. At the end, the first write slots hold the answer and you truncate once.
The code targets Python 3.12 and Java 21. One prerequisite: an array stores elements in a single contiguous block. Removing from the middle forces every later element to shift, which costs O(n) per removal (see the cost of shifting elements in an array). Big-O notation describes how running time grows as the input grows.
My position: never delete inside the loop. Overwrite, then truncate once. Treat write as the length of the answer rather than as a position in the input, and every in-place filter becomes the same five lines.
How to recognize when you need same direction two pointers
The signals are usually in the wording of the constraints rather than in the data itself.
- “In place” or “O(1) extra memory” plus “remove”, “keep”, or “compact”. You are filtering an array without building a second one.
- “Return the new length.” This phrasing means the caller will read only the prefix
nums[:k]. Whatever sits after indexk - 1does not matter. - “Keep the relative order.” The answer must be a stable filter. A forward read and write pass preserves order by construction.
- A sorted array with repeated values. Duplicates sit next to each other, so the writer only has to compare against what it wrote last.
- Two sorted inputs and one output buffer. Merging uses one read pointer per input and a write pointer into the output. If the buffer overlaps an input, write from the end.
If the question asks for the best contiguous range, such as the longest substring meeting some rule, you want a sliding window instead. If it asks for a pair with some sum, the pointers usually start at opposite ends.
The read and write invariant
At every moment the array splits into three regions. The prefix before write is the finished answer. The middle, from write up to read, is garbage you may overwrite. Everything from read onward is input you have not looked at yet.
index: 0 1 2 3 4 5 6
nums: [ 1 ][ 2 ][ 3 ][ 3 ][ 3 ][ 3 ][ 4 ]
\___________/ \______/ \______/
answer garbage unread
^ ^
write read
Rule: write <= read at all times, so a write never destroys unread input.
The invariant has two parts. First, nums[0:write] equals the correct output for the elements nums[0:read] of the original input. Second, write <= read. The first part makes the answer correct when read reaches the end. The second part makes the in-place trick safe, because every slot the writer touches has already been read.
Remove duplicates from a sorted array
The array is sorted, so all copies of a value are adjacent. Keep an element if it differs from the last element you kept, which is nums[write - 1]. Comparing with the last kept value, rather than with nums[read - 1], is the habit that makes the generalization below work.
The generalization allows each value at most k times. Compare the candidate with nums[write - k], the element k places back in the answer. If they are equal, sortedness means the last k kept elements are all that value, so one more copy would exceed the limit. With k = 1 this is exactly the dedupe rule.
In Python, with a brute-force cross-check on random inputs:
import random
from itertools import groupby
def remove_duplicates(nums: list[int]) -> int:
"""Keep one copy of each value in sorted nums, in place. Return the new length."""
if not nums:
return 0
write = 1 # nums[0] is always kept
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]: # differs from the last kept value
nums[write] = nums[read]
write += 1
return write
def keep_at_most(nums: list[int], k: int) -> int:
"""Keep each value at most k times (k >= 1) in sorted nums, in place."""
write = 0
for read in range(len(nums)):
if write < k or nums[read] != nums[write - k]:
nums[write] = nums[read]
write += 1
return write
def expected_at_most(nums: list[int], k: int) -> list[int]:
return [x for _, run in groupby(nums) for x in list(run)[:k]]
if __name__ == "__main__":
a = [1, 1, 2, 3, 3, 3, 4]
assert remove_duplicates(a) == 4 and a[:4] == [1, 2, 3, 4]
assert remove_duplicates([]) == 0
b = [7]
assert remove_duplicates(b) == 1 and b[:1] == [7]
c = [5, 5, 5, 5] # all duplicates
assert remove_duplicates(c) == 1 and c[:1] == [5]
d = [1, 1, 1, 2, 2, 3, 3, 3, 3]
assert keep_at_most(d, 2) == 6 and d[:6] == [1, 1, 2, 2, 3, 3]
assert keep_at_most([], 2) == 0
e = [4, 4, 4]
assert keep_at_most(e, 5) == 3 and e == [4, 4, 4] # k larger than any run
rng = random.Random(3)
for _ in range(500):
xs = sorted(rng.randint(0, 4) for _ in range(rng.randint(0, 12)))
k = rng.randint(1, 3)
ys = xs[:]
length = keep_at_most(ys, k)
assert ys[:length] == expected_at_most(xs, k), (xs, k)
print("PASS")
The same functions in Java. Java arrays cannot shrink, so the caller reads the first length slots:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class RemoveDuplicates {
static int removeDuplicates(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;
}
static int keepAtMost(int[] nums, int k) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (write < k || nums[read] != nums[write - k]) {
nums[write++] = nums[read];
}
}
return write;
}
static int[] expectedAtMost(int[] nums, int k) {
List<Integer> out = new ArrayList<>();
int run = 0;
for (int i = 0; i < nums.length; i++) {
run = (i > 0 && nums[i] == nums[i - 1]) ? run + 1 : 1;
if (run <= k) {
out.add(nums[i]);
}
}
return out.stream().mapToInt(Integer::intValue).toArray();
}
static void check(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
public static void main(String[] args) {
int[] a = {1, 1, 2, 3, 3, 3, 4};
int n = removeDuplicates(a);
check(n == 4 && Arrays.equals(Arrays.copyOf(a, n), new int[] {1, 2, 3, 4}), "normal");
check(removeDuplicates(new int[] {}) == 0, "empty");
check(removeDuplicates(new int[] {7}) == 1, "single");
int[] c = {5, 5, 5, 5};
check(removeDuplicates(c) == 1 && c[0] == 5, "all duplicates");
int[] d = {1, 1, 1, 2, 2, 3, 3, 3, 3};
n = keepAtMost(d, 2);
check(n == 6 && Arrays.equals(Arrays.copyOf(d, n), new int[] {1, 1, 2, 2, 3, 3}), "at most 2");
check(keepAtMost(new int[] {4, 4, 4}, 5) == 3, "k larger than run");
Random rng = new Random(3);
for (int t = 0; t < 500; t++) {
int[] xs = new int[rng.nextInt(13)];
for (int i = 0; i < xs.length; i++) {
xs[i] = rng.nextInt(5);
}
Arrays.sort(xs);
int k = 1 + rng.nextInt(3);
int[] ys = xs.clone();
int len = keepAtMost(ys, k);
check(Arrays.equals(Arrays.copyOf(ys, len), expectedAtMost(xs, k)), "random case " + t);
}
System.out.println("PASS");
}
}
Dry run: removing duplicates
Take nums = [1, 1, 2, 3, 3, 3, 4]. The writer starts at 1 because the first element is always kept.
| read | nums[read] | Last kept, nums[write – 1] | Action | write after | Answer prefix |
|---|---|---|---|---|---|
| 1 | 1 | 1 | Skip, same value | 1 | [1] |
| 2 | 2 | 1 | Copy to index 1 | 2 | [1, 2] |
| 3 | 3 | 2 | Copy to index 2 | 3 | [1, 2, 3] |
| 4 | 3 | 3 | Skip | 3 | [1, 2, 3] |
| 5 | 3 | 3 | Skip | 3 | [1, 2, 3] |
| 6 | 4 | 3 | Copy to index 3 | 4 | [1, 2, 3, 4] |
The function returns 4. Slots 4 to 6 still hold old values, and that is fine, because the contract says only the prefix counts. In Python you can finish with del nums[length:], which truncates in a single operation.
Move zeroes and remove element: stable vs unstable partition
A partition splits an array into two groups: elements you keep at the front and elements pushed to the back. A partition is stable when elements inside a group keep their original relative order. Interviewers care about this word, so define it before you code.
Move zeroes asks you to push every zero to the end while the non-zero values keep their order. The read and write loop does it with swaps instead of copies. Each non-zero value swaps into the write slot, and the zero that was there moves back toward the garbage region. The front group stays stable. The back group does not, though for zeroes nobody can tell.
Remove element has a weaker contract: drop every copy of a value, return the new length, and order does not matter. That allows an unstable trick. When you find the value, overwrite it with the last element and shrink the array, instead of shifting. If the value is rare, this does far fewer writes than the stable version, which copies almost every element.
In Python:
def move_zeroes(nums: list[int]) -> None:
"""Move zeroes to the end in place; non-zero values keep their order."""
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[write], nums[read] = nums[read], nums[write]
write += 1
def remove_element_stable(nums: list[int], val: int) -> int:
write = 0
for read in range(len(nums)):
if nums[read] != val:
nums[write] = nums[read]
write += 1
return write
def remove_element_unstable(nums: list[int], val: int) -> int:
"""Order of survivors may change; fewer writes when val is rare."""
i, n = 0, len(nums)
while i < n:
if nums[i] == val:
n -= 1
nums[i] = nums[n] # pull the last element in; re-check slot i
else:
i += 1
return n
if __name__ == "__main__":
a = [0, 3, 0, 5, 7]
move_zeroes(a)
assert a == [3, 5, 7, 0, 0]
for case in ([], [0], [1], [0, 0, 1]):
expected = [x for x in case if x != 0] + [0] * case.count(0)
move_zeroes(case)
assert case == expected
b = [2, 0, 2, 0] # duplicates
move_zeroes(b)
assert b == [2, 2, 0, 0]
c = [3, 1, 3, 2, 3]
n = remove_element_stable(c, 3)
assert n == 2 and c[:n] == [1, 2]
assert remove_element_stable([], 3) == 0
d = [3, 1, 3, 2, 3]
n = remove_element_unstable(d, 3)
assert n == 2 and sorted(d[:n]) == [1, 2]
e = [3, 3, 3] # every element removed
assert remove_element_unstable(e, 3) == 0
f = [1, 2, 3] # last element is the target
n = remove_element_unstable(f, 3)
assert n == 2 and sorted(f[:n]) == [1, 2]
print("PASS")
The same three functions in Java:
import java.util.Arrays;
public class Partitioning {
static void moveZeroes(int[] nums) {
int write = 0;
for (int read = 0; read < nums.length; read++) {
if (nums[read] != 0) {
int tmp = nums[write];
nums[write] = nums[read];
nums[read] = tmp;
write++;
}
}
}
static int removeElementStable(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;
}
static int removeElementUnstable(int[] nums, int val) {
int i = 0, n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[--n];
} else {
i++;
}
}
return n;
}
static void check(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
public static void main(String[] args) {
int[] a = {0, 3, 0, 5, 7};
moveZeroes(a);
check(Arrays.equals(a, new int[] {3, 5, 7, 0, 0}), "move zeroes");
int[] empty = {};
moveZeroes(empty);
check(empty.length == 0, "empty");
int[] single = {0};
moveZeroes(single);
check(single[0] == 0, "single");
int[] b = {0, 0, 1};
moveZeroes(b);
check(Arrays.equals(b, new int[] {1, 0, 0}), "leading zeroes");
int[] c = {3, 1, 3, 2, 3};
int n = removeElementStable(c, 3);
check(n == 2 && Arrays.equals(Arrays.copyOf(c, n), new int[] {1, 2}), "stable remove");
int[] d = {3, 1, 3, 2, 3};
n = removeElementUnstable(d, 3);
int[] kept = Arrays.copyOf(d, n);
Arrays.sort(kept);
check(n == 2 && Arrays.equals(kept, new int[] {1, 2}), "unstable remove");
check(removeElementUnstable(new int[] {3, 3, 3}, 3) == 0, "remove all");
System.out.println("PASS");
}
}
Note the subtle step in the unstable version: after pulling the last element into slot i, the loop does not advance i. The pulled element might also equal val, as it does for [3, 3, 3]. For a three-way split around a pivot, the Dutch National Flag three-way partition extends the same idea to three regions.
Merge two sorted arrays from the end
Here the first array has m sorted values followed by enough empty slots to hold the second array. Merge the second array into the first so the whole buffer ends up sorted. A forward merge fails: writing the smallest value into slot 0 overwrites a value of the first array you have not read yet.
Run the pointers backward instead. Compare the largest unread value of each input and write the larger one into the last free slot. The free slots sit at the end of the buffer, so the writer always lands on a slot that is empty or already consumed. When the second array runs out, whatever remains of the first array is already in place.
In Python:
def merge_into(a: list[int], m: int, b: list[int]) -> None:
"""a holds m sorted values then len(b) free slots. Merge sorted b into a."""
i, j, write = m - 1, len(b) - 1, m + len(b) - 1
while j >= 0:
if i >= 0 and a[i] > b[j]:
a[write] = a[i]
i -= 1
else:
a[write] = b[j] # ties take b first, so equal values from a stay in front
j -= 1
write -= 1
if __name__ == "__main__":
a = [1, 4, 7, 0, 0, 0]
merge_into(a, 3, [2, 4, 9])
assert a == [1, 2, 4, 4, 7, 9]
b = [0, 0]
merge_into(b, 0, [3, 5]) # first array empty
assert b == [3, 5]
c = [1, 2]
merge_into(c, 2, []) # second array empty
assert c == [1, 2]
d = [5, 6, 0, 0]
merge_into(d, 2, [1, 2]) # every value of b is smaller
assert d == [1, 2, 5, 6]
e = [2, 2, 0, 0]
merge_into(e, 2, [2, 2]) # duplicates across both inputs
assert e == [2, 2, 2, 2]
print("PASS")
The same merge in Java:
import java.util.Arrays;
public class MergeFromEnd {
static void mergeInto(int[] a, int m, int[] b) {
int i = m - 1, j = b.length - 1, write = m + b.length - 1;
while (j >= 0) {
if (i >= 0 && a[i] > b[j]) {
a[write--] = a[i--];
} else {
a[write--] = b[j--];
}
}
}
static void check(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
public static void main(String[] args) {
int[] a = {1, 4, 7, 0, 0, 0};
mergeInto(a, 3, new int[] {2, 4, 9});
check(Arrays.equals(a, new int[] {1, 2, 4, 4, 7, 9}), "normal");
int[] b = {0, 0};
mergeInto(b, 0, new int[] {3, 5});
check(Arrays.equals(b, new int[] {3, 5}), "first empty");
int[] c = {1, 2};
mergeInto(c, 2, new int[] {});
check(Arrays.equals(c, new int[] {1, 2}), "second empty");
int[] d = {5, 6, 0, 0};
mergeInto(d, 2, new int[] {1, 2});
check(Arrays.equals(d, new int[] {1, 2, 5, 6}), "all smaller");
int[] e = {2, 2, 0, 0};
mergeInto(e, 2, new int[] {2, 2});
check(Arrays.equals(e, new int[] {2, 2, 2, 2}), "duplicates");
System.out.println("PASS");
}
}
The trace below merges b = [2, 4, 9] into a = [1, 4, 7, _, _, _] with m = 3.
| Step | i (a[i]) | j (b[j]) | Write index | Value written | Buffer after |
|---|---|---|---|---|---|
| 1 | 2 (7) | 2 (9) | 5 | 9 from b | [1, 4, 7, _, _, 9] |
| 2 | 2 (7) | 1 (4) | 4 | 7 from a | [1, 4, 7, _, 7, 9] |
| 3 | 1 (4) | 1 (4) | 3 | 4 from b (tie) | [1, 4, 7, 4, 7, 9] |
| 4 | 1 (4) | 0 (2) | 2 | 4 from a | [1, 4, 4, 4, 7, 9] |
| 5 | 0 (1) | 0 (2) | 1 | 2 from b | [1, 2, 4, 4, 7, 9] |
After step 5, j is -1 and the loop stops. The 1 at index 0 never moved, because it was already in its final slot.
Complexity of same direction two pointers
Each pointer only moves forward (or only backward, for the merge), and each move is constant work. So every variant below runs in a single linear pass.
| Operation | Time (worst case) | Extra space | Stable? |
|---|---|---|---|
| Remove duplicates, keep at most k | O(n) |
O(1) |
Yes |
| Remove element, copy version | O(n) |
O(1) |
Yes |
| Remove element, swap with last | O(n) |
O(1) |
No |
| Move zeroes with swaps | O(n) |
O(1) |
Front group only |
| Merge sorted arrays from the end | O(m + n) |
O(1) |
Yes, ties favor the first array |
| Calling remove inside a loop | O(n^2) |
O(1) |
Yes, but too slow |
You can measure the last row yourself. This script removes zeroes from a 20,000-element list twice, once with repeated list.remove and once with the read and write pass:
import random
import timeit
def remove_zeroes_naive(nums: list[int]) -> None:
while 0 in nums:
nums.remove(0) # scans, then shifts the tail left
def remove_zeroes_two_pointer(nums: list[int]) -> None:
write = 0
for read in range(len(nums)):
if nums[read] != 0:
nums[write] = nums[read]
write += 1
del nums[write:] # truncate once
if __name__ == "__main__":
rng = random.Random(5)
data = [rng.choice((0, rng.randint(1, 9))) for _ in range(20_000)]
x, y = data[:], data[:]
remove_zeroes_naive(x)
remove_zeroes_two_pointer(y)
assert x == y == [v for v in data if v != 0]
for name, fn in (("naive remove", remove_zeroes_naive),
("read/write", remove_zeroes_two_pointer)):
seconds = timeit.timeit(lambda: fn(data[:]), number=1)
print(f"{name:13} {seconds:.4f} s")
Double the list size and run it again. The naive time should grow about four times, while the read and write pass roughly doubles. Your exact numbers depend on your machine; the growth ratio is the point.
How this differs from a sliding window and from fast and slow pointers
All three patterns move two indices left to right, which is why people confuse same direction two pointers with the other two. The difference is what the region between the pointers means.
- Read and write pointers. The answer is the prefix before
write. The region betweenwriteandreadis garbage. The writer moves only when an element is kept. - Sliding window. The region between the pointers is the candidate answer itself, a contiguous range of the input. The right end grows it and the left end shrinks it until a condition holds again. The variable-size sliding window for longest and shortest substrings covers that invariant.
- Fast and slow pointers. The two pointers move at different fixed speeds, usually one and two steps. That speed ratio finds a cycle or the middle of a list. See fast and slow pointers for cycle detection and the middle node.
When pointers start at opposite ends and close in, you are in a different family again: opposite-direction two pointers for pair sums and palindromes.
Where this shows up in real systems
- Java’s
ArrayList.removeIf. The defaultremoveIfinCollectionremoves matching elements one by one through an iterator, per the OpenJDK 21 Collection.java source. For an array-backed list, each such removal shifts the tail. - The override. The OpenJDK 21 ArrayList.java source replaces that with two passes. It first marks doomed elements in a bit set, then copies survivors forward with a write index
w(es[w++] = es[i]) and clears the tail once. - Merging runs in CPython’s
list.sort. The CPython 3.12 listsort.txt notes describe two merge routines. When the right run is smaller,merge_hicopies it to a temporary array and merges right to left, starting the stores at the right end. It is the merge-from-the-end trick inside a production sort.
The ArrayList source comment also explains why it reads everything before writing anything. A predicate that reads the list while it runs sees it unchanged, because no element moves until every predicate call has finished.
How to explain it in an interview
- Start with the naive approach. “Removing inside the loop shifts the tail each time, so it is
O(n^2)in the worst case.” - Name the bottleneck. “The shifts are the cost. I never need to delete, only to decide where each kept element goes.”
- State the invariant. “
nums[0:write]is the answer for everything read so far, andwritenever passesread.” - Write the loop. Keep the keep-condition in one
if, so the reader of your code can check it in isolation. - Give complexity.
O(n)time in the worst case andO(1)extra space. - Walk the edge cases. Empty input, one element, all elements kept, all removed, and long runs of duplicates.
Common follow-ups include “allow each value twice”, “does your solution keep the order?”, “can you do fewer writes?”, and “what if the buffer is at the front?”. A strong answer handles the first with nums[write - k] and names stability explicitly. It offers swap-with-last for fewer writes, and it explains that overlapping buffers force writing from whichever end is free.
A mistake I see often when candidates generalize remove duplicates to “at most twice”: they compare nums[read] with nums[read - 2] instead of nums[write - 2]. It passes simple examples, then drops a valid copy on input like [1, 1, 1, 2, 2], because the writer has already overwritten slot read - 2. The fix is one character, but finding it requires knowing that the answer lives behind write.
Decision framework for in-place array filtering
- Must the result keep the original order? If yes, use the forward copy loop. If no, swap-with-last does fewer writes when removals are rare.
- Is extra memory actually forbidden? If not, a Python list comprehension or a Java stream filter is clearer and also
O(n)time, at the cost ofO(n)extra space. - Does the keep rule depend only on the element and what you kept? Then a single read and write pass works. Compare against
nums[write - 1]ornums[write - k], never against stale read-side values. - Does the output buffer overlap an unread input? Write from the end that is free. For a merge into a buffer with trailing space, that end is the back.
- Is the answer a contiguous range of the input? Then you need a sliding window, not a read and write filter.
When not to use read and write pointers
- Unsorted duplicate removal. On unsorted input, duplicates are not adjacent, so comparing with the last kept value misses them. Use a hash set to track seen values, or sort first if order does not matter.
- Immutable data or shared lists. Python strings and tuples cannot be modified, and an in-place filter on a list someone else holds is a side effect they did not ask for. Build a new sequence instead.
- Linked lists. Removing a node is already
O(1)once you hold its predecessor, so there is no shifting to avoid. Relink nodes with a dummy head rather than copying values.
Common mistakes
- Deleting while iterating. In Python,
for x in nums: nums.remove(x)skips the element after each removal. On[0, 0, 1], removing zeroes leaves[0, 1]. - Comparing against the read side. Checking
nums[read - 2]for “at most twice” fails on[1, 1, 1, 2, 2]. It returns[1, 1, 2], because the writer put a 2 into slot 2 before the reader compared against it. - Advancing after the swap-with-last. Incrementing
iafter pulling in the last element skips a check. On[3, 3]with value 3, it returns 1 instead of 0. - Merging from the front into a shared buffer. On
a = [4, 5, _, _]andb = [1, 2], writing 1 into slot 0 destroys the 4 before it is read. - Forgetting the empty input. A dedupe that starts with
write = 1returns 1 for an empty array unless you return 0 first. - Returning the array and ignoring the length. In Java the array keeps its old size. Tests that compare the whole array instead of the first
lengthslots fail on the garbage tail.
The first mistake is the one that ships to production, so here it is in full. The wrong version mutates the list it is iterating over:
for x in nums: # WRONG: the iterator's index moves past shifted elements
if x == 0:
nums.remove(x)
The right version reads every element exactly once and truncates at the end.
write = 0
for read in range(len(nums)): # RIGHT: overwrite, then truncate once
if nums[read] != 0:
nums[write] = nums[read]
write += 1
del nums[write:]
On [0, 0, 1], the wrong loop removes the zero at index 0. The list shifts to [0, 1], the iterator moves on to index 1, and it sees 1. The second zero is never checked. In Java, the same pattern with a for-each loop over an ArrayList throws ConcurrentModificationException on that input instead of silently returning a wrong answer.
Practice problems
| Problem | Difficulty | The twist |
|---|---|---|
| Remove Element | Easy | The base template; try both the stable and swap-with-last versions |
| Remove Duplicates from Sorted Array | Easy | Compare with the last kept value |
| Move Zeroes | Easy | Swap instead of copy so the zeroes end up at the back |
| Merge Sorted Array | Easy | Write from the end because the buffer overlaps the first input |
| Is Subsequence | Easy | One pointer per string; the short string’s pointer moves only on a match |
| Sort Array By Parity | Easy | An unstable partition where order does not matter |
| Remove Duplicates from Sorted Array II | Medium | Compare with nums[write - 2] |
| String Compression | Medium | The writer emits a character plus its run count, still never passing the reader |
Key takeaways
- Never delete inside the loop. With same direction two pointers you overwrite kept elements at
write, then truncate once. - Hold the invariant:
nums[0:write]is the answer so far andwrite <= read. - Compare against what you kept,
nums[write - k], not against what you read. - Say whether your partition is stable. Copy loops are; swap-with-last is not.
- When the output buffer overlaps unread input, write from the free end. For merges into trailing space, that is the back.
- Tell this pattern apart from sliding windows: here the region between the pointers is garbage, not the answer.
Frequently Asked Questions
What is the difference between same direction and opposite direction two pointers?
Opposite direction pointers start at both ends and move toward each other, which suits pair sums and palindromes. Same direction pointers both move left to right, with a write pointer trailing a read pointer, which suits in-place filtering and compaction.
How do you remove duplicates from a sorted array in place?
Keep a write index for the next free slot and scan with a read index. Copy an element to the write slot only when it differs from the last value you kept, then return the write index as the new length. This runs in O(n) time with constant extra space.
Why merge sorted arrays from the end instead of the front?
The free slots sit at the end of the first array, so writing from the back only touches slots that are empty or already read. Writing from the front would overwrite values of the first array before they are compared.
Is the move zeroes solution a stable partition?
The swap loop keeps the non-zero values in their original order, so the front group is stable. The back group can be reordered by the swaps, which only goes unnoticed because every element there is zero.
The write pointer marks the end of the answer
Every problem here reduces to one question per element: does it belong in the answer? If yes, it goes to write and write advances. If no, the reader moves on and the slot gets overwritten later. Keep that picture of a growing answer prefix and you will not reach for a delete inside a loop again. More patterns built on the same habit of proving an invariant first are collected in the DSA Playbook.
Rule of thumb: in-place filtering is overwrite then truncate, never delete while you scan.
Originally posted on 4 December 2026 and post last modified on 4 December 2026