Remove Element · Optimal Solution

Write pointer skips the target value.

A baggage scanner flags items of a specific weight for removal from a conveyor. A write pointer holds position while a read pointer inspects every item — anything that doesn't match the target slides forward to the write position and advances it. Flagged items are simply skipped. After one pass the belt holds only permitted items at the front, and the write pointer reports the new count. O(n) time. O(1) space.


Interactive

Watch the algorithm run


Concept

Read/Write Pointer

A read pointer scans every element. A write pointer tracks where the next keeper should land. When the read pointer finds a non-target value, it copies it to the write position and both advance. When it finds the target, only the read pointer moves — the write pointer stays put, effectively skipping the match.


Algorithm

Algorithm

A single forward pass skips every occurrence of the target value. Non-target elements are compacted to the front of the array.

  1. 1

    Initialize write pointer

    Set write = 0. Every non-target value will be compacted to the front starting here.

  2. 2

    Scan each element

    For each read from 0 to n − 1, compare nums[read] with val.

  3. 3

    Copy if not target

    If nums[read] ≠ val, copy it to nums[write] and advance write.

  4. 4

    Return count

    After the scan, write equals the number of elements that are not val.


Edge Cases

Edge Patterns

Understanding boundary behavior is as important as the main algorithm path.

No matches

The target value does not appear. Every element is copied, and the write pointer reaches n — the array is unchanged.

All matches

Every element equals val. The write pointer never advances — the result length is 0.


Complexity

Complexity

Time: O(n) — single pass.
Space: O(1) — in-place with two pointers.