Repair a Sensor Log: Merge, Sort, and Interpolate Gaps
Arrays & HashingAuto-graded · 22 test casesLast updated
Merge duplicate timestamps by averaging known readings, sort, then fill missing values by linear interpolation inside gaps and nearest-value holding at the ends.
Repair a Sensor Log: Merge, Sort, and Interpolate Gaps
A sensor produces a log of readings. Each entry is a pair [timestamp, value], where timestamp is an integer and value is either a floating-point number or null, which means the reading was lost.
The log may be in any order, and a timestamp can show up in several entries. Produce a repaired log by following these rules in order.
-
Combine entries with the same timestamp.
- If at least one entry for that timestamp has a non-
nullvalue, the combined value is the arithmetic mean of the non-nullvalues only. Entries withnullare ignored in the average. - If every entry for that timestamp is
null, the timestamp becomes one missing point.
- If at least one entry for that timestamp has a non-
-
Sort the combined points by timestamp, ascending.
-
Interpolate inside gaps. Take a missing point at time
tthat has a known point somewhere before it and a known point somewhere after it. Let(t1, v1)be the closest known point witht1 < t, and(t2, v2)the closest known point witht2 > t. Its value isv = v1 + (v2 - v1) * (t - t1) / (t2 - t1)Only original known values (after step 1) are used as
v1andv2, never values that were filled in. -
Hold values at the ends. A missing point earlier than every known point takes the value of the earliest known point. A missing point later than every known point takes the value of the latest known point.
Return the repaired log as a list of [timestamp, value] pairs, one per distinct timestamp, sorted by timestamp ascending, with every value a float.
Input
records: a list ofnpairs[timestamp, value], wherevalueis a float ornull(Nonein Python).
Output
- A list of
[timestamp, value]pairs, one per distinct timestamp, in ascending timestamp order, with all values filled in as floats.
Constraints
1 <= n <= 10^5-10^9 <= timestamp <= 10^9- Known values satisfy
-10^6 <= value <= 10^6 - At least one record has a known (non-
null) value. - Answers within an absolute error of
10^-6are accepted.
Examples
Example 1
Input: repair_sensor_log([[3, None], [1, 10], [5, 20], [3, None]])
Output: [[1, 10], [3, 15], [5, 20]]
Example 2
Input: repair_sensor_log([[2, 4], [2, 6], [4, None], [6, 8], [0, None]])
Output: [[0, 5], [2, 5], [4, 6.5], [6, 8]]
Hints
Hint 1
Group the records by timestamp, keeping a running sum and a count of only the non-null values. A count of zero means the timestamp is a missing point.
Hint 2
After sorting the distinct timestamps, collect the indices of the known points. Every missing point lies either before the first known index, after the last, or between two consecutive known indices.
Hint 3
For each pair of consecutive known indices, the left and right ones are exactly the nearest known neighbours of every missing point between them, so you can interpolate that whole stretch in one pass without searching.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task breaks into three passes: group, sort, then fill.
- Group by timestamp. Keep a running total and a count of known values for each timestamp in two dictionaries. A
nullrecord registers the timestamp but adds nothing to the total or the count. After the pass,total / countis the mean of the known values, andcount == 0marks a timestamp whose records were allnull. - Sort the distinct timestamps and build a parallel list of values, using
Nonefor the missing ones. - Fill using the indices of the known points:
- Every index before the first known index copies the first known value.
- For each pair of consecutive known indices, every index strictly between them is interpolated with the given formula.
- Every index after the last known index copies the last known value.
Why it is correct
- Each timestamp's sum and count cover exactly its known values, so the mean ignores
nullentries. A timestamp with onlynullrecords has count zero and is treated as missing. The dictionary keys are distinct, so there is exactly one output pair per timestamp. - For two consecutive known indices there is no known point between them, so they are the nearest known neighbours of every missing point in between. That is exactly the
(t1, v1)and(t2, v2)the formula needs. - Interpolation reads only the original known values, never filled ones, so the fill order does not matter.
- The leading range, the interior gaps and the trailing range together cover every missing index. At least one known value is guaranteed, so the known list is not empty.
- The denominator
t2 - t1is positive because timestamps are distinct after merging.
Complexity
- Time:
O(n + m log m), wherem <= nis the number of distinct timestamps. This isO(n log n)in the worst case. - Space:
O(m).
Reference solution
from typing import List, Optional
def repair_sensor_log(records: List[List[Optional[float]]]) -> List[List[float]]:
totals = {}
counts = {}
for timestamp, value in records:
if timestamp not in totals:
totals[timestamp] = 0.0
counts[timestamp] = 0
if value is not None:
totals[timestamp] += value
counts[timestamp] += 1
points = sorted(totals)
values = [totals[t] / counts[t] if counts[t] else None for t in points]
known = [i for i, v in enumerate(values) if v is not None]
first = known[0]
for i in range(first):
values[i] = values[first]
for left, right in zip(known, known[1:]):
t1, t2 = points[left], points[right]
v1, v2 = values[left], values[right]
for i in range(left + 1, right):
values[i] = v1 + (v2 - v1) * (points[i] - t1) / (t2 - t1)
last = known[-1]
for i in range(last + 1, len(points)):
values[i] = values[last]
return [[timestamp, float(value)] for timestamp, value in zip(points, values)]