Skip to content

Remove Element

EasyTwo Pointers
Decode it first. Clues, constraints, pattern and plan before any code.

Given a list nums and a value val, remove every occurrence of val in place. Return k, the number of elements that are not val. The first k slots of nums must hold those elements, in any order; whatever comes after them does not matter.

nums = [3, 2, 2, 3],             val = 3   →  k = 2, first two are [2, 2]
nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 2   →  k = 5, first five are 0, 1, 3, 0, 4 in some order

Constraints

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100
  • Use O(1) extra space.