All problems

Stuck Sensor Trim

Medium · two pointers

A weather station logs a temperature reading every minute. Sometimes the sensor gets stuck and keeps repeating the same value. The list readings holds the log in order.

To clean it up, the station keeps at most k readings from any run of equal readings that sit next to each other. In a run longer than k, the first k readings are kept and the rest are dropped. Equal values that are separated by a different reading belong to different runs and are treated separately.

Return the cleaned log as a new list, with the kept readings in their original order.

Examples

Example 1

Input: readings = [5, 5, 5, 5, 7, 5, 5], k = 2

Output: [5, 5, 7, 5, 5]

The first run of 5s has four readings, so only two stay. The 5s after the 7 are a new run of two, which is fine.

Example 2

Input: readings = [1, 2, 3], k = 1

Output: [1, 2, 3]

No two neighbours are equal, so nothing is dropped.

Example 3

Input: readings = [4, 4, 4], k = 1

Output: [4]

With k = 1 each run keeps only its first reading.

Constraints