KatInterview

Simulate Stream Price Volatility Monitor

Data Structure DesignAuto-graded · 14 test cases
EasyAuto-gradedData Structure Designdesign-dssimulationstate-management

Last 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 to 0).
  • previous_price: stores the price ingested immediately before last_price (initialized to 0).

Process a list of operations paired with their respective arguments. The supported operations are:

  1. "update": Ingests a new price given in arguments[i][0] (a positive integer). Before updating last_price to the new value, the current value of last_price must be moved to previous_price. This operation yields None.
  2. "get_volatility": Returns the absolute difference between last_price and previous_price as an integer (abs(last_price - previous_price)).
  3. "get_average": Returns the arithmetic mean of last_price and previous_price as a floating-point value ((last_price + previous_price) / 2.0).

Constraints

  • operations is a list of strings containing only "update", "get_volatility", or "get_average".
  • arguments is a list of lists corresponding element-wise to operations.
    • For "update", arguments[i] contains a single positive integer (price >= 1).
    • For "get_volatility" and "get_average", arguments[i] is an empty list [].
  • 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]