#27

Remove Element

Easy Read/write pointers

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Remove every occurrence of val from the array in place and return how many elements are left. Order of the rest may change.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: drop every copy of val, in place.

Why this works: copy everything that isn't val to the write position; whatever is left behind doesn't matter.

Example: [3, 2, 2, 3], val = 3

3 skip, 2 → [2], 2 → [2, 2], 3 skiplength 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using list.remove in a loop on a converted list — it shifts elements and costs O(n²).