You are given multiple time series representing asset values in a financial portfolio. Each time series is a list of [date, value] pairs sorted by date in ascending order. Dates are represented as integers (for example, days since epoch).
Not all time series have data points on the same dates. Merge all time series into a single sorted timeline. For each date that appears in any time series, output the value of every asset on that date.
If an asset does not have a data point on a particular date, carry forward its most recent previous value. If no previous value exists, use 0.
Return a list of lists where the first element is the date and the remaining elements are the asset values in the order the time series were given.
Function Signature
def merge_timeseries(series: list[list[list[int]]]) -> list[list[int]]:
Rules
-
series[i]
is the time series of asset
i
, given as a list of
[date, value]
pairs. A series may be empty.
-
The output has exactly one row per distinct date across all series, and the rows are sorted by date in ascending order.
-
Each row is
[date, value_0, value_1, ..., value_(n-1)]
, where
n = len(series)
and
value_i
is the value of asset
i
on that date after carrying forward.
-
If no series has any data points, return
[]
.
Constraints
-
1 <= number of time series <= 100
-
0 <= length of each time series <= 1000
-
0 <= date <= 10^9
-
-10^9 <= value <= 10^9
-
Each time series is sorted by date in ascending order.
-
Dates within a single time series are unique.
Examples
Input: series = [[[1, 100], [3, 150], [5, 200]], [[2, 50], [3, 75], [4, 80]]]
Output: [[1, 100, 0], [2, 100, 50], [3, 150, 75], [4, 150, 80], [5, 200, 80]]
The distinct dates are 1 to 5. On date 1 asset 1 has no data yet, so it is 0. On dates 2 and 4 asset 0 carries forward its last value, and on date 5 asset 1 carries forward 80.
Input: series = [[[10, 500]], [[5, 300], [10, 400], [15, 600]], [[5, 100], [20, 200]]]
Output: [[5, 0, 300, 100], [10, 500, 400, 100], [15, 500, 600, 100], [20, 500, 600, 200]]
Asset 0 has nothing before date 10, so it is 0 on date 5 and 500 from date 10 on. Asset 2 keeps 100 through dates 10 and 15 until its next point on date 20.
Input: series = [[[2, 7]], []]
Output: [[2, 7, 0]]
Only date 2 appears. Asset 1 has no data at all, so its value stays 0.