Simulate Stream Price Volatility Monitor
Data Structure DesignAuto-graded · 14 test casesLast updated
Execute stateful stream commands to maintain the two most recent values and calculate their difference and floating-point average.
You are tasked with building a stateful data monitor that processes continuous numeric updates and answers queries about the two most recent data points.
The system tracks two state variables:
last_price: stores the most recently ingested price (initialized to0).previous_price: stores the price ingested immediately beforelast_price(initialized to0).
Process a list of operations paired with their respective arguments. The supported operations are:
"update": Ingests a new price given inarguments[i][0](a positive integer). Before updatinglast_priceto the new value, the current value oflast_pricemust be moved toprevious_price. This operation yieldsNone."get_volatility": Returns the absolute difference betweenlast_priceandprevious_priceas an integer (abs(last_price - previous_price))."get_average": Returns the arithmetic mean oflast_priceandprevious_priceas a floating-point value ((last_price + previous_price) / 2.0).
Constraints
operationsis a list of strings containing only"update","get_volatility", or"get_average".argumentsis a list of lists corresponding element-wise tooperations.- For
"update",arguments[i]contains a single positive integer (price >= 1). - For
"get_volatility"and"get_average",arguments[i]is an empty list[].
- For
- If an unsupported operation string is encountered, raise a
ValueError. 1 <= len(operations) <= 10^4.- Output must be a list containing the result of each operation in order.
Examples
Example 1
Input: market_tracker_operations(['update', 'update', 'get_volatility', 'get_average'], [[10], [20], [], []])
Output: [None, None, 10, 15]
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem asks us to simulate a state tracker holding the two most recent price inputs, starting with initial values of 0 for both previous_price and last_price.
When processing operations sequentially:
update(price): We shiftlast_priceintoprevious_price, then assign the incomingpricetolast_price. Using Python's concurrent assignmentprevious_price, last_price = last_price, priceor explicitly savingprevious_price = last_pricebefore updatinglast_priceavoids overwriting state incorrectly. This appendsNoneto the output list.get_volatility(): We computeabs(last_price - previous_price)and return the integer result.get_average(): We calculate(last_price + previous_price) / 2.0to return a floating-point number representing the mean of the two stored values.- Invalid operations: If an unrecognized operation name is provided, raise a
ValueError.
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of operations. Each operation performs constant-time $\mathcal{O}(1)$ state updates or arithmetic calculations.
- Space Complexity: $\mathcal{O}(N)$ to construct and return the
resultslist containing the output of each operation.
Reference Solution
from typing import List
def market_tracker_operations(operations: List[str], arguments: List[List[object]]) -> List[object]:
previous_price = 0
last_price = 0
results = []
for op, args in zip(operations, arguments):
if op == "update":
previous_price = last_price
last_price = args[0]
results.append(None)
elif op == "get_volatility":
results.append(abs(last_price - previous_price))
elif op == "get_average":
results.append((last_price + previous_price) / 2.0)
else:
raise ValueError(f"Unknown operation: {op}")
return results