27/670

27. Remove Element

Easy

You receive an integer array nums and an integer val. Delete every occurrence of val from the array in place and return k, the number of elements that survive.

After your function finishes, the first k slots of nums must contain the surviving elements in their original relative order; whatever remains past index k - 1 is ignored. Try to do it in one pass without allocating a second array.

Example 1:

Input: nums = [3, 2, 2, 3], val = 3

Output: 2, with nums starting [2, 2, _, _]

Explanation: Both 3s are dropped; the two 2s slide to the front in their original order, so k = 2.

Example 2:

Input: nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2

Output: 5, with nums starting [0, 1, 3, 0, 4, ...]

Explanation: Removing every 2 leaves 0, 1, 3, 0, 4 — five elements, still in the order they originally appeared.

Constraints:

  • 0 ≤ nums.length ≤ 2 * 10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • -10⁴ ≤ val ≤ 10⁴
  • Surviving elements must keep their original relative order.

Hints:

You never need to physically delete anything — you only need the keepers packed at the front and a correct count.

Maintain a 'write' index that always points at the next free slot of the kept prefix. Scan with a read index; every time nums[read] != val, copy it to nums[write] and bump write.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [3, 2, 2, 3], val = 3

Expected output: k = 2, nums → [2, 2]