All problems
0279MediumArrayTwo Pointers

Trim Repeats in the Depth Log

Tracked in this browser only
Write code

Trains the technique from

LeetCode 80Remove Duplicates from Sorted Array II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def trim_repeat_readings(readings: list[int]) -> int:
Java
public int trimRepeatReadings(int[] readings)
September 7
Apply