Remove Element

easy array two pointers in-place

Problem

Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed.

Inputnums = [3, 2, 2, 3, 4, 3], val = 3
Output3, with nums starting [2, 2, 4, …]
Three 3's are removed; the kept values 2, 2, 4 fill the front in their original order.

def remove_element(nums, val):
    w = 0
    for r in range(len(nums)):
        if nums[r] != val:
            nums[w] = nums[r]
            w += 1
    return w
function removeElement(nums, val) {
  let w = 0;
  for (let r = 0; r < nums.length; r++) {
    if (nums[r] !== val) {
      nums[w++] = nums[r];
    }
  }
  return w;
}
class Solution {
    public int removeElement(int[] nums, int val) {
        int w = 0;
        for (int r = 0; r < nums.length; r++) {
            if (nums[r] != val) {
                nums[w++] = nums[r];
            }
        }
        return w;
    }
}
int removeElement(vector<int>& nums, int val) {
    int w = 0;
    for (int r = 0; r < nums.size(); r++) {
        if (nums[r] != val) {
            nums[w++] = nums[r];
        }
    }
    return w;
}
Time: O(n) Space: O(1)