AlgoInsight

DSA problem

Stock Price Fluctuation

MediumBST / Ordered SetPattern: BST / Ordered Settop150AmazonMicrosoftGoogleBloombergTwo Sigma

You are given a stream of records of a single stock's price at various timestamps. Records may arrive out of order, and a later record at the same timestamp corrects (overrides) the previous price for that timestamp. Implement a StockPrice class supporting four operations:

update(timestamp, price) records or corrects the price at timestamp. current() returns the price at the most recent timestamp seen so far. maximum() returns the maximum price across all (timestamp, price) records currently in effect. minimum() returns the minimum price across all records currently in effect. All four operations must run efficiently — ideally O(log n) per call.

The challenges are the out-of-order updates and the corrections. A simple hash map from timestamp to price handles current() in O(1) (just track latestTimestamp). For min/max, a heap that does not support efficient deletion would still work using lazy deletion, but the cleanest design uses a sorted multiset (or TreeMap of price -> count) that supports O(log n) insert, delete, and min/max lookups.

The optimal design therefore uses three structures: (1) timestampToPrice: Map<int, int> for current price at each timestamp; (2) priceCounts: TreeMap<int, int> mapping each price to the number of timestamps holding that price; and (3) latestTimestamp. On update(t, p): if t already has an old price, decrement its count (and remove the entry if it falls to zero); then set the new mapping and increment priceCounts[p]; if t >= latestTimestamp, update latestTimestamp and remember current is p. Min/max read the first/last key of priceCounts in O(log n).

Examples

Example 1
Input: ["StockPrice","update","update","current","maximum","update","maximum","update","minimum"] [[],[1,10],[2,5],[],[],[1,3],[],[4,2],[]]
Output: [null,null,null,5,10,null,5,null,2]
Explanation: After (1,10) and (2,5): current()=5 (latest ts is 2), maximum()=10. Update (1,3) replaces ts1's price; maximum is now 5 (since 10 was removed). After (4,2): minimum()=2.
Example 2
Input: ["StockPrice","update","update","minimum","update","maximum"] [[],[1,1],[2,2],[],[1,3],[]]
Output: [null,null,null,1,null,3]
Explanation: After (1,1) and (2,2): minimum=1. Update (1,3): timestamp 1's price changes from 1 to 3; current set is {3, 2}, so maximum=3.
Example 3
Input: ["StockPrice","update","current","update","current"] [[],[5,100],[],[3,50],[]]
Output: [null,null,100,null,100]
Explanation: After (5,100): current()=100. Then (3,50) arrives out of order; since 3 < 5, latestTimestamp stays at 5, so current()=100.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

designordered-sethash-tableheapsorted-set

Browse all DSA problems