#27
Remove Element
Easy Read/write pointers
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Remove every occurrence of val from the array in place and return how many elements are left. Order of the rest may change.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: drop every copy of val, in place.
Why this works: copy everything that isn't val to the write position; whatever is left behind doesn't matter.
Example: [3, 2, 2, 3], val = 3
3 skip, 2 → [2], 2 → [2, 2], 3 skiplength 2
✦Hints open one at a time
Copy every element that is not val to the next write position.
Everything after the write position doesn't matter.
↗Approach
One read pointer scans; a write pointer receives the elements to keep.
</>Solution (Java)
class Solution {
public int removeElement(int[] nums, int val) {
int write = 0;
for (int x : nums) {
if (x != val) nums[write++] = x;
}
return write;
}
}
!Common mistake
Using list.remove in a loop on a converted list — it shifts elements and costs O(n²).
Complexity
- Time: O(n).
- Space: O(1).
