Skip to main content
Back to problems
Leetcode
Easy
Arrays
Two Pointers
Remove Element

Remove all occurrences of a target value from an array in-place and return the new length.

Acceptance 0%
Problem Statement

You are given an integer array nums and an integer val. Remove every occurrence of val from nums in-place so that the remaining elements occupy the beginning of the array.

The relative order of the remaining elements does not need to be preserved unless stated otherwise. Return the number of elements left after removal.

After the function finishes, only the first returned elements of nums should be considered valid.

Input Format

  • An integer array nums
  • An integer val to remove

Output Format

Return an integer representing the number of elements in nums that are not equal to val.

Constraints

  • Modify the array in-place using O(1)O(1) extra space when possible.
  • The order of kept elements may be changed unless the implementation chooses to preserve it.
  • Assume nums can be empty.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

2

Explanation

Remove all 3s. The first two positions of the array can contain the remaining values, such as [2,2].

Example 2

Input

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

Output

5

Explanation

After removing 2s, five elements remain, for example [0,1,3,0,4].

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.