Median of a Data Stream
Process an ordered sequence of commands for a streaming-median data structure. An ADD command inserts one integer, and a MEDIAN command queries the median of all values inserted so far.
Function Signature
stream_median_queries(operations: list[list[str]]) -> list[float]
Valid Input Domain
Each operation is either ["ADD", value], where value is a base-10 signed 32-bit integer encoded as text, or ["MEDIAN"]. Every MEDIAN occurs after at least one ADD.
Exact Output Semantics
Return one result for each MEDIAN command, in command order. For an odd number of inserted values, the median is the middle sorted value. For an even number, it is the arithmetic mean of the two middle values. Results are integers or half-integers represented as floating-point values. When averaging two middle values, promote both operands to signed 64-bit arithmetic before adding and dividing by 2.0.
Constraints
-
0 <= operations.length <= 200,000
.
-
Every inserted value is between
-2,147,483,648
and
2,147,483,647
inclusive.
Public Examples
Example 1
Input: operations = [["ADD", "5"], ["ADD", "2"], ["MEDIAN"], ["ADD", "10"], ["MEDIAN"]]
Output: [3.5, 5.0]
Only explicit MEDIAN commands produce output.
Example 2
Input: operations = [["ADD", "2147483647"], ["ADD", "2147483647"], ["MEDIAN"], ["ADD", "-2147483648"], ["MEDIAN"]]
Output: [2147483647.0, 2147483647.0]
The first query requires adding two maximum signed 32-bit values safely.
Hints
-
Maintain a lower half and an upper half whose sizes differ by at most one.
-
A query should inspect the two boundary values without re-sorting the entire stream.