Intuition
Keep a slow write-pointer for the next kept slot. Scan with a fast pointer; whenever the current value is not the one to remove, copy it to the slow slot and advance. The slow pointer ends as the count of kept elements.
Explanation
Idea
We want the surviving elements packed at the front. A slow/fast two-pointer sweep does this in one pass: fast reads every element; slow marks where the next kept element goes. Skipping the values equal to val leaves the kept elements compacted at the front, in their original order.
(This platform returns the resulting kept array — its length is the required k.)
Algorithm
k = 0.- For each
xinnums: ifx != val, writenums[k] = xandk += 1. - The first
kelements are the answer; returnnums[:k].
Worked example: nums = [3,2,2,3], val = 3
- 3 == val → skip. 2 ≠ val → nums[0]=2, k=1. 2 ≠ val → nums[1]=2, k=2. 3 == val → skip.
Kept = [2,2] (k = 2).
Complexity
- Time: O(n) — one pass.
- Space: O(1) — in place.
Implementation
import java.util.Arrays;
class Solution {
public int[] removeElement(int[] nums, int val) {
int k = 0;
for (int x : nums) {
if (x != val) {
nums[k] = x;
k++;
}
}
return Arrays.copyOf(nums, k);
}
}