Remove Element - Problem

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.

Consider the number of elements in nums which are not equal to val be k. To get accepted, you need to do the following things:

Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.

Return k.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,2,3], val = 3
Output: 2
💡 Note: Remove all occurrences of 3. The first 2 elements become [2,2], so return 2.
Example 2 — No Target Elements
$ Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5
💡 Note: Remove all occurrences of 2. The first 5 elements become [0,1,3,0,4], so return 5.
Example 3 — All Elements Same
$ Input: nums = [2,2,2], val = 2
Output: 0
💡 Note: All elements equal the target value, so no elements remain. Return 0.

Constraints

  • 0 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 50
  • 0 ≤ val ≤ 100

Visualization

Tap to expand
Remove Element ProblemInput: nums = [3,2,2,3], val = 33223TargetKeepKeepTargetRemove all 3'sResult: First k=2 elements are valid22xxOutput: k = 2
Understanding the Visualization
1
Input
Array with some elements equal to target value
2
Process
Remove all occurrences of target value in-place
3
Output
Count of remaining elements after removal
Key Takeaway
🎯 Key Insight: Use two pointers to efficiently rearrange elements in-place without extra memory
Asked in
Facebook 25 Google 20 Amazon 15
125.0K Views
High Frequency
~15 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen