◀ THE GRIND — ARRAYS & HASHING

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.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

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.

EX 01
nums = [3, 2, 2, 3] · val = 3
2
TARGET VALUE BOOKENDS THE ARRAY
EX 02
nums = [0, 1, 2, 2, 3, 0, 4, 2] · val = 2
5
TARGET SCATTERED THROUGH THE ARRAY
EX 03
nums = [1] · val = 1
0
SINGLE ELEMENT, ENTIRELY REMOVED
THE HINTS — TAKE ONLY WHAT YOU NEED
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.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE READER AND THE WRITERPATTERN · TWO-POINTER OVERWRITEnums = [3, 2, 2, 3] · val = 3
3
2
2
3
STEP 1

nums = [3, 2, 2, 3], val = 3. A reader scans forward; a writer packs survivors at the front.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/remove-element.pyRACE PACE
LANG ▸
PACE ▸
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 writer
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 8 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED