Skip to main content

Aggregate Two Time Series - Solution & Explanation

MediumArrayTwo Pointers10 min read
Practice this problem

Problem Statement

You are given two 2D integer arrays series1 and series2.

Each element in both series is of the form [timestamp, value], where:

  • timestamp is an integer representing the time.
  • value is an integer representing the value at that timestamp.

Each array is sorted in strictly increasing order of timestamp.

For any timestamp not present in a series, its value is taken from the next available timestamp in the same series if one exists. Otherwise, its value is considered 0.

The aggregated series is formed by summing the corresponding values from both series at every timestamp that appears in either series.

Return the aggregated series as a 2D integer array of [timestamp, summedValue] pairs, sorted in strictly increasing order of timestamp.

 

Example 1:

Input: series1 = [[1,3],[4,1]], series2 = [[2,2],[5,2]]

Output: [[1,5],[2,3],[4,3],[5,2]]

Explanation:

Timestamp series1 series2 summedValue
1 3 2 5
2 1 2 3
4 1 2 3
5 0 2 2

Thus, the aggregated series is [[1, 5], [2, 3], [4, 3], [5, 2]].

Example 2:

Input: series1 = [[1,5],[3,1]], series2 = [[2,2]]

Output: [[1,7],[2,3],[3,1]]

Explanation:

Timestamp series1 series2 summedValue
1 5 2 7
2 1 2 3
3 1 0 1

Thus, the aggregated series is [[1, 7], [2, 3], [3, 1]].

Example 3:

Input: series1 = [[1,5]], series2 = [[1000000000,2]]

Output: [[1,7],[1000000000,2]]

Explanation:

At timestamp 1, the next available value in series2 is 2 at timestamp 1000000000. At timestamp 1000000000, there is no later timestamp in series1, so its value is 0. Only timestamps that appear in at least one of the two series are included.

 

Constraints:

  • 1 <= series1.length, series2.length <= 105
  • series1[i].length == series2[i].length == 2
  • 1 <= series1[i][0], series2[i][0] <= 109
  • 1 <= series1[i][1], series2[i][1] <= 109
  • Each series is sorted in strictly increasing order of timestamp.

Approach Overview

Problem Overview: You are given two time series datasets where each entry contains a timestamp and a value. The goal is to combine both series into a single aggregated result by timestamp. Matching timestamps should have their values summed, while unique timestamps should still appear in the final output.

Approach 1: Brute Force Comparison (Time: O(n * m), Space: O(1))

The direct solution compares every entry in the first series against every entry in the second series. For each timestamp match, you aggregate the values and mark the pair as processed. After the nested iteration finishes, append the remaining unmatched timestamps. This approach works for small datasets and helps verify correctness before optimizing, but repeated scans make it inefficient for large inputs.

Approach 2: Hash Map Aggregation (Time: O(n + m), Space: O(n + m))

Use a hash map where the key is the timestamp and the value is the running aggregate. Iterate through the first series and insert values into the map. Then iterate through the second series and update existing timestamps or create new entries. After processing both arrays, convert the map into the required output format and sort by timestamp if needed. This is the standard solution for unsorted input because hash lookup runs in constant average time. Problems involving hash tables and arrays frequently use this pattern.

Approach 3: Two Pointers on Sorted Series (Time: O(n + m), Space: O(1) extra)

If both time series are already sorted by timestamp, two pointers produce the cleanest solution. Start one pointer at the beginning of each series. Compare timestamps: when they match, append the summed value and move both pointers; otherwise append the smaller timestamp and move the corresponding pointer. After one series finishes, append the remaining elements from the other series. This avoids hash table overhead and preserves sorted order naturally. The same technique appears in two pointers and merge-style interval problems.

Recommended for interviews: Interviewers typically expect the hash map or two-pointer approach depending on whether the input is sorted. The brute force version demonstrates baseline reasoning, but the optimized O(n + m) solution shows that you recognize aggregation patterns and understand how to reduce repeated scans. If sorted order is guaranteed, two pointers are usually preferred because they achieve linear time with minimal extra memory.

Solution

Both series are strictly increasing by timestamp, so they can be merged with two pointers. Taking the value of the next later timestamp for a missing timestamp is equivalent to: the value at the current pointer can be used directly for earlier missing timestamps in that series.

Let pointers i and j point to the two series. While both are not exhausted:

  • If t_1 = t_2, output [t_1, v_1 + v_2] and advance both pointers;
  • If t_1 < t_2, output [t_1, v_1 + v_2] (series2 uses the current later v_2) and advance only i;
  • If t_2 < t_1, handle symmetrically.

After one series is exhausted, append the remaining points of the other series directly (there is no later timestamp on the opposite side, so its value is 0).

The time complexity is O(m + n), and the space complexity is O(m + n), where m and n are the lengths of the two series.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force ComparisonO(n * m)O(1)Small datasets or validating correctness first
Hash Map AggregationO(n + m)O(n + m)General case with unsorted timestamps
Two Pointers on Sorted SeriesO(n + m)O(1)When both series are already sorted

Video Solution

LeetCode 4001 | Aggregate Two Time Series | Two Pointers + Merge | Java | Hindi • Code Kage • 170 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Aggregate Two Time Series easy or hard?
Aggregate Two Time Series is generally considered a medium-level problem. The core logic is straightforward, but choosing the right strategy based on sorted versus unsorted input is what interviewers evaluate. Candidates are expected to optimize beyond brute force.
Aggregate Two Time Series Python/Java solution
Python solutions typically use dictionaries or collections.defaultdict for aggregation. Java implementations commonly use HashMap<Integer, Integer> or TreeMap when sorted output is required. Both languages support an O(n + m) implementation.
How to solve Aggregate Two Time Series in O(n)?
Use a hash map or two pointers depending on the input format. With a hash map, iterate through both series once and accumulate values by timestamp. If the series are sorted, two pointers merge them in a single pass while aggregating matching timestamps.
What is the best approach for Aggregate Two Time Series?
The best approach depends on whether the input series are sorted. For unsorted data, a hash map aggregation solution runs in O(n + m) time and handles duplicate timestamps efficiently. If both series are sorted by timestamp, a two-pointer merge approach achieves the same linear complexity with lower extra memory usage.
Is Aggregate Two Time Series asked at Google/Amazon/Meta?
Time series aggregation and merge-style problems appear frequently in backend and data-processing interview rounds at companies like Google, Amazon, and Meta. Interviewers often test hash maps, sorting, and linear merge strategies through variations of this problem.
What data structure is used in Aggregate Two Time Series?
The most common data structure is a hash map keyed by timestamp. It allows constant average-time insertion and lookup while aggregating values. Sorted input variants often use arrays with the two-pointer technique instead of extra storage.
What is the time complexity of Aggregate Two Time Series?
The optimal solution runs in O(n + m) time, where n and m are the sizes of the two time series. Hash map aggregation and two-pointer merging both process each entry once. A brute force comparison approach takes O(n * m) time and is not suitable for large datasets.

Ready to solve this problem?

Practice Aggregate Two Time Series with our built-in code editor and test cases.

Practice on FleetCode