Remove Element - Problem
Remove Element In-Place

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 elements

Example: 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
๐Ÿ“š Library Book Organization Analogy๐Ÿ“š Bookshelf - Remove Horror Books (H)๐Ÿ“–Horror๐Ÿ“˜Fiction๐Ÿ“—Mystery๐Ÿ“–HorrorReaderWriterAfter Organization๐Ÿ“š Organized Shelf - Horror Books Removed๐Ÿ“˜Fiction๐Ÿ“—Mysteryโˆ…โˆ…โœ… Result: 2 books kept (writer final position = 2)๐Ÿ’ก Key Insight: We don't physically remove, just overwrite positions!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two pointer variables

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค nums.length โ‰ค 100
  • -100 โ‰ค nums[i] โ‰ค 100
  • -100 โ‰ค val โ‰ค 100
  • Must modify array in-place
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
89.0K Views
Very High Frequency
~15 min Avg. Time
3.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