Stock Price Fluctuation

MEDIUM

Description

You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp.

Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record.

Design an algorithm that:

  • Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp.
  • Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded.
  • Finds the maximum price the stock has been based on the current records.
  • Finds the minimum price the stock has been based on the current records.

Implement the StockPrice class:

  • StockPrice() Initializes the object with no price records.
  • void update(int timestamp, int price) Updates the price of the stock at the given timestamp.
  • int current() Returns the latest price of the stock.
  • int maximum() Returns the maximum price of the stock.
  • int minimum() Returns the minimum price of the stock.

 

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
StockPrice stockPrice = new StockPrice();
stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].
stockPrice.update(2, 5);  // Timestamps are [1,2] with corresponding prices [10,5].
stockPrice.current();     // return 5, the latest timestamp is 2 with the price being 5.
stockPrice.maximum();     // return 10, the maximum price is 10 at timestamp 1.
stockPrice.update(1, 3);  // The previous timestamp 1 had the wrong price, so it is updated to 3.
                          // Timestamps are [1,2] with corresponding prices [3,5].
stockPrice.maximum();     // return 5, the maximum price is 5 after the correction.
stockPrice.update(4, 2);  // Timestamps are [1,2,4] with corresponding prices [3,5,2].
stockPrice.minimum();     // return 2, the minimum price is 2 at timestamp 4.

 

Constraints:

  • 1 <= timestamp, price <= 109
  • At most 105 calls will be made in total to update, current, maximum, and minimum.
  • current, maximum, and minimum will be called only after update has been called at least once.

Approaches

Checkout 3 different approaches to solve Stock Price Fluctuation . Click on different approaches to view the approach and algorithm in detail.

Optimized `current()` using TreeMap

This approach improves upon the brute-force method by using a TreeMap to store the timestamp-price data. A TreeMap keeps its keys (timestamps) sorted, which allows for efficient retrieval of the latest price, but finding the minimum and maximum prices still requires a full scan.

Algorithm

  • Initialize a TreeMap<Integer, Integer> to store timestamp-price records, which keeps them sorted by timestamp.
  • For update(timestamp, price), use map.put(timestamp, price). This takes O(log N) time.
  • For current(), retrieve the last key (the maximum timestamp) from the TreeMap using lastKey() and get its value. This takes O(log N) time.
  • For maximum() and minimum(), iterate through all values in the TreeMap, which still takes O(N) time.

By replacing the HashMap with a TreeMap<Integer, Integer>, we can optimize the current() operation. A TreeMap is a sorted map that maintains its entries in ascending order of keys.

  • update(timestamp, price): We insert or update the key-value pair in the TreeMap. This operation takes O(log N) time, as the map needs to maintain its sorted order.
  • current(): Since the TreeMap is sorted by timestamp, the latest timestamp is simply the last key in the map. We can retrieve this using records.lastKey() in O(log N) time and then get its corresponding price.
  • maximum(): To find the maximum price, we still need to iterate through all the values in the TreeMap. This remains an O(N) operation.
  • minimum(): Similarly, finding the minimum price requires iterating through all values, taking O(N) time.
class StockPrice {
    TreeMap<Integer, Integer> records;

    public StockPrice() {
        records = new TreeMap<>();
    }

    public void update(int timestamp, int price) {
        records.put(timestamp, price);
    }

    public int current() {
        // lastKey() gives the highest timestamp in O(log N)
        return records.get(records.lastKey());
    }

    public int maximum() {
        int maxPrice = 0;
        for (int price : records.values()) {
            maxPrice = Math.max(maxPrice, price);
        }
        return maxPrice;
    }

    public int minimum() {
        int minPrice = Integer.MAX_VALUE;
        for (int price : records.values()) {
            minPrice = Math.min(minPrice, price);
        }
        return minPrice;
    }
}

Complexity Analysis

Time Complexity: - `update`: O(log N). - `current`: O(log N). - `maximum`: O(N). - `minimum`: O(N).Space Complexity: O(N), where N is the number of unique timestamps, to store the records in the `TreeMap`.

Pros and Cons

Pros:
  • The current() operation is significantly faster (O(log N)) than in the brute-force approach.
  • The implementation is still relatively simple.
Cons:
  • The maximum() and minimum() operations remain inefficient with O(N) time complexity.
  • The update operation is slightly slower (O(log N)) than the pure HashMap approach (O(1)).

Code Solutions

Checking out 3 solutions in different languages for Stock Price Fluctuation . Click on different languages to view the code.

class StockPrice { private Map < Integer , Integer > d = new HashMap <>(); private TreeMap < Integer , Integer > ls = new TreeMap <>(); private int last ; public StockPrice () { } public void update ( int timestamp , int price ) { if ( d . containsKey ( timestamp )) { int old = d . get ( timestamp ); if ( ls . merge ( old , - 1 , Integer: : sum ) == 0 ) { ls . remove ( old ); } } d . put ( timestamp , price ); ls . merge ( price , 1 , Integer: : sum ); last = Math . max ( last , timestamp ); } public int current () { return d . get ( last ); } public int maximum () { return ls . lastKey (); } public int minimum () { return ls . firstKey (); } } /** * Your StockPrice object will be instantiated and called as such: * StockPrice obj = new StockPrice(); * obj.update(timestamp,price); * int param_2 = obj.current(); * int param_3 = obj.maximum(); * int param_4 = obj.minimum(); */

Video Solution

Watch the video walkthrough for Stock Price Fluctuation



Patterns:

DesignData Stream

Data Structures:

Hash TableHeap (Priority Queue)Ordered Set

Subscribe to Scale Engineer newsletter

Learn about System Design, Software Engineering, and interview experiences every week.

No spam, unsubscribe at any time.