Remove Element(#27)

Category: Array, Two Pointer

🧩 Problem Statement

You are given an array nums and an integer val. Your task is to remove all occurrences of val from the array in-place, and return the number of elements that are not equal to val. The modified array should have all the remaining (non-val) elements at the beginning. The rest of the elements don’t matter. Return the count k, which is the number of elements not equal to val.

πŸ“š Examples

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

Output: 2

Explanation: Modified array: [2,2,_,_]. First 2 elements are not equal to 3.

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

Output: 5

Explanation: Modified array: [0,1,3,0,4,_,_,_]. First 5 elements are not equal to 2.

🧠 Approach

Approach 1:

Two Pointer (Swap Based)

β€’ Initialize two pointers `first = 0` and `sec = 0`.

β€’ Loop while `sec < nums.length`.

β€’ If `nums[sec] !== val`, swap `nums[first]` and `nums[sec]`, and increment `first`.

β€’ Always increment `sec`.

Approach 2:

Cleaner Overwrite

β€’ Initialize a pointer `k = 0`.

β€’ Loop through each element in `nums`.

β€’ If the element is not equal to `val`, overwrite `nums[k] = nums[i]`.

β€’ Increment `k` after each overwrite.

πŸ’» Code

// Approach 1: Two Pointer (Swap Based)
var removeElement = function(nums, val) {
  let first = 0;
  let sec = 0;

  while (sec < nums.length) {
    if (nums[sec] !== val) {
      [nums[first], nums[sec]] = [nums[sec], nums[first]];
      first++;
    }
    sec++;
  }

  console.log(nums.slice(0, first));
  return first;
};

console.log(removeElement([3,2,2,3], 3)); // Output: 2
console.log(removeElement([0,1,2,2,3,0,4,2], 2)); // Output: 5


// Approach 2: Cleaner Overwrite
var removeElement = function(nums, val) {
  let k = 0;

  for (let i = 0; i < nums.length; i++) {
    if (nums[i] !== val) {
      nums[k] = nums[i];
      k++;
    }
  }

  console.log(nums.slice(0, k));
  return k;
};

console.log(removeElement([3,2,2,3], 3)); // Output: 2
console.log(removeElement([0,1,2,2,3,0,4,2], 2)); // Output: 5

πŸ“ˆ Complexity

Time: O(n) – We iterate through the array once.

Space: O(1) – Done in-place without extra space.

🎬 Watch Explanation

πŸ“Š Presentation (PPT)

πŸ“₯ Download PPT

πŸ“Ž Resources