Remove Element

Easy#27same direction

You get an array of numbers and one number, val. Get rid of every copy of val inside the same array, without a second one, and return how many numbers are left. Those numbers must fill the start of the array, in any order; what lies after them does not matter. Our example: [4, 1, 4, 4, 2, 3], val = 4 → 3, and the array starts with [1, 2, 3].

input
nums: integers; val: the number to remove.
returns
k, how many numbers of nums are not val. Change nums in place so that its first k items are those numbers, in any order; what is left after them does not matter.
constraints
  • 0 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 50
  • 0 ≤ val ≤ 100
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
function removeElement(nums, val) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.