easy

Remove Element

Remove every occurrence of a value from an array in place.

1. Define the problem

Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in place . The order of the remaining elements may change. Return k, the number of elements that are not equal to val, after moving them to the front of nums. Use a slow pointer that marks the next write position, and a fast pointer that scans the array, copying over only the values that should be kept.

Constraints

  • 0 ≤ nums.length ≤ 100
  • 0 ≤ numsi ≤ 50
  • 0 ≤ val ≤ 100

Example

Inputnums = [3, 2, 2, 3], val = 3
Output2, nums = [2, 2, ...]

Explanation The function returns k = 2, and the first two elements of nums are both 2.

2. Know the words first

In plain terms

In place
Making the change directly inside the given array instead of building a new one, using little to no extra memory.
3. Visualize the solution

Slow pointer writes kept values, fast pointer scans

Slow pointer writes kept values, fast pointer scans
Statusinit

slow=0, fast=0 (value 3), which equals val=3. Skip it, slow stays.

What happens in this step

slow = 0, fast = 0 (value 3)
nums[fast] == val (3 == 3)

Skip this element — do not write it, and slow does not move.
Step 1 of 4

Steps to visualize

  1. Start slow at index 0.
  2. Advance fast through the array from the start.
  3. Whenever numsfast is not val, copy it into numsslow and move slow forward.
  4. Skip over any value equal to val without writing it.
  5. The final value of slow is the count of elements kept.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Slow pointer writes kept values, fast pointer scans
Statusinit

slow=0, fast=0 (value 3), which equals val=3. Skip it, slow stays.

What happens in this step

slow = 0, fast = 0 (value 3)
nums[fast] == val (3 == 3)

Skip this element — do not write it, and slow does not move.
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function removeElement(nums, val) {
  let slow = 0;

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

  return slow;
}
Time
O(n)
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
nums = [3, 2, 2, 3], val = 32example from the docstring
nums = [], val = 50smallest valid input, an empty array
nums = [2, 2, 2], val = 20every element equals val, nothing is kept
nums = [1, 2, 3], val = 93val never appears, every element is kept
nums = [0, 1, 2, 2, 3, 0, 4, 2], val = 25val scattered throughout a longer array
nums = [7], val = 70single element that matches val