Remove Duplicates from Sorted Array II
Real-world version: Trim Repeats in the Depth LogThe statement here is our own: the same inputs, outputs and technique.
A depth probe files one figure per sample into readings, measured in metres against sea level, so a sample taken below the surface is negative. The probe files them in non-decreasing order.
The log is too repetitive to archive as it stands: no figure may appear more than twice. Rewrite readings so that the figures which survive sit at the front of the array in the order they were filed, and return the count k of survivors. Whatever sits at index k and beyond in the array afterwards is disregarded.
Carry out the rewrite inside the array you were handed, using only a constant amount of extra space rather than assembling a second array.
Examples
Example 1
- Input
- readings = [-5, -5, -5, 0, 0, 7]
- Output
- 5
The figure -5 was filed three times, so one copy goes. The first five slots become -5, -5, 0, 0, 7 and the count 5 is returned.
Example 2
- Input
- readings = [0, 0, 0, 0, 0]
- Output
- 2
Two copies of 0 are allowed to stay, so the first two slots hold 0 and 0 and the count 2 is returned.
Example 3
- Input
- readings = [-3, -1, 4]
- Output
- 3
No figure was filed twice, so all three slots stay as they are and the count 3 is returned.
Constraints
- 1 <= readings.length <= 3 * 10^4
- -10^4 <= readings[i] <= 10^4
- readings is sorted in non-decreasing order.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def trim_repeat_readings(readings: list[int]) -> int:public int trimRepeatReadings(int[] readings)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 8 test cases: 8 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's