Remove Element - Problem
Remove Element In-Place
You're given an integer array
๐ฏ The Challenge:
โข Modify the array directly (no extra array allowed)
โข The order of remaining elements can be changed
โข Return
โข The first
Example: If
Note: The elements after position k don't matter - they can be anything!
You're given an integer array
nums and a target value val. Your mission is to remove all occurrences of val from the array in-place and return the count of remaining elements.๐ฏ The Challenge:
โข Modify the array directly (no extra array allowed)
โข The order of remaining elements can be changed
โข Return
k = number of elements that are NOT equal to valโข The first
k elements should contain all the valid elementsExample: If
nums = [3,2,2,3] and val = 3, after removal you should have [2,2,_,_] and return k = 2.Note: The elements after position k don't matter - they can be anything!
Input & Output
example_1.py โ Python
$
Input:
nums = [3,2,2,3], val = 3
โบ
Output:
2
๐ก Note:
Remove all occurrences of 3. The array becomes [2,2,_,_] where underscores represent irrelevant values. Return k=2 since there are 2 elements not equal to 3.
example_2.py โ Python
$
Input:
nums = [0,1,2,2,3,0,4,2], val = 2
โบ
Output:
5
๐ก Note:
Remove all occurrences of 2. The array becomes [0,1,4,0,3,_,_,_]. Return k=5 since there are 5 elements not equal to 2.
example_3.py โ Python
$
Input:
nums = [1], val = 1
โบ
Output:
0
๐ก Note:
The single element equals val, so remove it. The array becomes [_] and return k=0 since no elements remain.
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Place two bookmarks: 'reader' at start, 'writer' at start
2
Scan
Reader checks each book - is it the genre we want to remove?
3
Keep Good Books
If book is good, move it to writer position and advance writer
4
Skip Bad Books
If book is target genre, just move reader (don't advance writer)
5
Result
Writer position shows count of books kept
Key Takeaway
๐ฏ Key Insight: Use two pointers to avoid expensive shifting operations - just overwrite unwanted elements with valid ones!
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with constant work per element
โ Linear Growth
Space Complexity
O(1)
Only using two pointer variables
โ Linear Space
Constraints
- 0 โค nums.length โค 100
- -100 โค nums[i] โค 100
- -100 โค val โค 100
- Must modify array in-place
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code