Remove Element
The drill: Clear every occurrence of one value out of an array in place, packing whatever survives at the front in any order, then report how many values remain. Judged here on the returned count, the same in-place compaction lesson as trimming duplicates.
An array of integers and a single target value arrive together, and every occurrence of that target needs to disappear from the array — done in place, without allocating a second array.
The survivors don't need to keep their original relative order; they just need to end up packed at the front of the array, occupying its first however-many slots.
Anything left sitting past that packed prefix is irrelevant and never inspected — what actually gets judged is the count of survivors, reported as the return value.
- arrays hold up to roughly a hundred elements on this course
- the target value may or may not appear in the array at all
- survivor order after the target is removed is unconstrained
- the returned count, not the leftover tail of the array, is what's checked
HINT 1 THE NUDGE
Copying every non-target value into a fresh array works, but the whole point of the exercise is skipping that fresh array. What lets you overwrite instead of allocate?
HINT 2 THE STRUCTURE
Survivors don't need to keep their original order, only their values — so a boundary index can mark 'everything before this is already a keeper' while a second pointer keeps reading ahead.
HINT 3 ONE STEP FROM THE ANSWER
Walk the array with a reader; whenever nums[reader] isn't the target, write it into nums[writer] and advance writer. Skip it otherwise. Writer's final position is the count you return.
nums = [3, 2, 2, 3], val = 3. A reader scans forward; a writer packs survivors at the front.
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
writer = 0
for x in nums:
if x != val:
nums[writer] = x
writer += 1
return writerclass Solution:
def removeElement(self, nums: List[int], val: int) -> int:
kept = [x for x in nums if x != val] # fresh list of survivors
for i, x in enumerate(kept):
nums[i] = x
return len(kept)class Solution {
public int removeElement(int[] nums, int val) {
int writer = 0;
for (int x : nums) {
if (x != val) {
nums[writer++] = x;
}
}
return writer;
}
}class Solution {
public int removeElement(int[] nums, int val) {
List<Integer> kept = new ArrayList<>();
for (int x : nums) {
if (x != val) {
kept.add(x);
}
}
for (int i = 0; i < kept.size(); i++) {
nums[i] = kept.get(i);
}
return kept.size();
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED