Deleting from the middle of an array is slow because every later element has to shift. A common trick is to not shrink the list at all: overwrite the values you want to keep at the front and return how many there are. Callers then only read the first k slots.
A data logger keeps its readings in nums and writes the value val whenever a reading fails. Clean the log in place: gather every value that is not val into the front of nums and return how many there are, k. Only nums[0] to nums[k - 1] are read afterwards, so those slots must hold exactly the kept values (in any order), and whatever is left beyond them does not matter. Each test calls kept(nums, val), which runs your function and returns k together with the first k values of nums, sorted.
Examples
Input: nums = [4, 9, 9, 4, 9], val = 9
Output: 2
After: the first 2 slots of nums contain 4 and 4
Input: nums = [6, 0, 6, 6, 3, 0, 9, 6], val = 6
Output: 4
After: the first 4 slots of nums contain 0, 0, 3, 9 in some order
Constraints
0 <= len(nums) <= 1000- Modify
numsin place; the tests readnums[:k]after the call.
Goals
- Overwrite unwanted values in place and report how many elements remain
- Recognise the 'return the new length' convention used by many array problems