Back to solutions

Remove Element

EasyArrays

Remove all occurrences of a value in place and return the new length.

Constraints
  • 0 <= n <= 100
  • 0 <= nums[i], val <= 50

Write pointer (overwrite)

Time O(n)Space O(1)

Keep a write index k. Scan the array; every time the current value is not val, copy it to position k and advance k. After the scan the first k slots hold all the kept elements and k is the new length.

Key terms
write pointer:
An index marking where the next kept element should be placed.
in place:
Rearranging within the original array with no extra array allocated.
int removeElement(vector<int>& nums, int val) {
    int k = 0;
    for (int x : nums) if (x != val) nums[k++] = x;
    return k;
}
Step by step
  1. Set k = 0.
  2. For each value x, if x != val, write it at nums[k] and increment k.
  3. Values equal to val are simply skipped, so they get overwritten.
  4. Return k as the count of kept elements.