Back to solutions
Remove Element
EasyArraysRemove 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
- Set k = 0.
- For each value x, if x != val, write it at nums[k] and increment k.
- Values equal to val are simply skipped, so they get overwritten.
- Return k as the count of kept elements.