Remove Element

(#27), Easy

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]`, then increment `first`.
  • Always increment `sec` regardless of condition.
// Approach 1
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++;
  }
  return first;
};

Approach 2: Cleaner Overwrite

  • Initialize a pointer `k = 0`.
  • Loop through the array using index `i`.
  • If `nums[i] !== val`, set `nums[k] = nums[i]` and increment `k`.
  • `k` will be the count of elements not equal to val.
// Approach 2
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++;
    }
  }
  return k;
};

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