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 - Optimal Solution INPUT nums array: 3 [0] 2 [1] 2 [2] 3 [3] = val (remove) = keep Value to remove: val = 3 nums=[3,2,2,3], val=3 ALGORITHM STEPS 1 Initialize Pointer k = 0 (write position) 2 Iterate Array Check each element 3 Keep Valid Elements If nums[i] != val: nums[k++] = nums[i] 4 Return k Count of kept elements Process: i=0: 3==3 --> skip i=1: 2!=3 --> nums[0]=2, k=1 i=2: 2!=3 --> nums[1]=2, k=2 i=3: 3==3 --> skip FINAL RESULT Modified array: 2 [0] 2 [1] ? [2] ? [3] first k elements Output: k = 2 Verification: First 2 elements = [2,2] OK - No 3s in first k! Key Insight: Two-pointer approach uses ONE write pointer (k) while iterating with read pointer (i). Elements != val are written at position k, then k increments. This achieves O(n) time and O(1) space. TutorialsPoint - Remove Element | Two-Pointer Optimal Approach
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