← Visualizers
Two Pointers · read/write compaction LeetCode 27

Remove Element / visualized

Two pointers travelling the same direction at different speeds: a slow write head marking the slot the next kept value goes into, and a fast read head scanning ahead. Anything that isn't val gets copied back to write; anything that is simply never gets copied. The invariant is the whole problem — nums[0, write) is a finished answer after every single step, the order of what survives is irrelevant, and everything past the returned length is junk.

Execution

idle
[0, write) — kept write — next slot stale / unread
Press Run to begin.
0 / 0
Speed

Java · running line

write (slow) read (fast) kept prefix dropped / stale
O(n) time · O(1) extra space  ·  one pass, at most one write per read. The function returns a length, not an array: nums[k..n) may hold anything.