Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
**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 <= 10^9
  • At most 10^5 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.

Solution

Method 1 - HashMap + Heaps (Priority Queues)

Intuition

We need to support fast updates, and fast queries for the latest, max, and min prices. Use a hashmap for timestamp→price, and two heaps (max-heap and min-heap) for price queries. When a price is updated, we may have stale entries in the heaps, so we lazily remove them when querying.

Approach

  • Use a hashmap to store the latest price for each timestamp.
  • Track the latest timestamp.
  • Use a max-heap and min-heap to store (price, timestamp) pairs.
  • For maximum/minimum, pop from the heap until the price matches the current price for that timestamp.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <unordered_map>
#include <queue>
using namespace std;
class StockPrice {
    unordered_map<int, int> time2price;
    priority_queue<pair<int, int>> maxHeap;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> minHeap;
    int latest = 0;
public:
    void update(int timestamp, int price) {
        time2price[timestamp] = price;
        latest = max(latest, timestamp);
        maxHeap.emplace(price, timestamp);
        minHeap.emplace(price, timestamp);
    }
    int current() { return time2price[latest]; }
    int maximum() {
        while (maxHeap.top().first != time2price[maxHeap.top().second]) maxHeap.pop();
        return maxHeap.top().first;
    }
    int minimum() {
        while (minHeap.top().first != time2price[minHeap.top().second]) minHeap.pop();
        return minHeap.top().first;
    }
};
1
2
// Go does not have built-in heap with remove, so use a map and sort for max/min
// For production, use a custom heap with lazy deletion
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
class StockPrice {
    Map<Integer, Integer> time2price = new HashMap<>();
    PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
    PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
    int latest = 0;
    public void update(int timestamp, int price) {
        time2price.put(timestamp, price);
        latest = Math.max(latest, timestamp);
        maxHeap.offer(new int[]{price, timestamp});
        minHeap.offer(new int[]{price, timestamp});
    }
    public int current() { return time2price.get(latest); }
    public int maximum() {
        while (maxHeap.peek()[0] != time2price.get(maxHeap.peek()[1])) maxHeap.poll();
        return maxHeap.peek()[0];
    }
    public int minimum() {
        while (minHeap.peek()[0] != time2price.get(minHeap.peek()[1])) minHeap.poll();
        return minHeap.peek()[0];
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*
class StockPrice {
    private val time2price = mutableMapOf<Int, Int>()
    private val maxHeap = PriorityQueue(compareByDescending<Pair<Int, Int>> { it.first })
    private val minHeap = PriorityQueue(compareBy<Pair<Int, Int>> { it.first })
    private var latest = 0
    fun update(timestamp: Int, price: Int) {
        time2price[timestamp] = price
        latest = maxOf(latest, timestamp)
        maxHeap.add(price to timestamp)
        minHeap.add(price to timestamp)
    }
    fun current() = time2price[latest]!!
    fun maximum(): Int {
        while (maxHeap.peek().first != time2price[maxHeap.peek().second]) maxHeap.poll()
        return maxHeap.peek().first
    }
    fun minimum(): Int {
        while (minHeap.peek().first != time2price[minHeap.peek().second]) minHeap.poll()
        return minHeap.peek().first
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import heapq
class StockPrice:
    def __init__(self):
        self.time2price = {}
        self.maxHeap = []  # (-price, timestamp)
        self.minHeap = []  # (price, timestamp)
        self.latest = 0
    def update(self, timestamp: int, price: int) -> None:
        self.time2price[timestamp] = price
        self.latest = max(self.latest, timestamp)
        heapq.heappush(self.maxHeap, (-price, timestamp))
        heapq.heappush(self.minHeap, (price, timestamp))
    def current(self) -> int:
        return self.time2price[self.latest]
    def maximum(self) -> int:
        while -self.maxHeap[0][0] != self.time2price[self.maxHeap[0][1]]:
            heapq.heappop(self.maxHeap)
        return -self.maxHeap[0][0]
    def minimum(self) -> int:
        while self.minHeap[0][0] != self.time2price[self.minHeap[0][1]]:
            heapq.heappop(self.minHeap)
        return self.minHeap[0][0]
1
// Rust: Use BTreeMap for min/max, or use BinaryHeap with lazy deletion
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class StockPrice {
    private time2price = new Map<number, number>();
    private maxHeap: [number, number][] = [];
    private minHeap: [number, number][] = [];
    private latest = 0;
    update(timestamp: number, price: number): void {
        this.time2price.set(timestamp, price);
        this.latest = Math.max(this.latest, timestamp);
        this.maxHeap.push([price, timestamp]);
        this.minHeap.push([price, timestamp]);
    }
    current(): number {
        return this.time2price.get(this.latest)!;
    }
    maximum(): number {
        while (this.maxHeap.length && this.maxHeap[0][0] !== this.time2price.get(this.maxHeap[0][1])) {
            this.maxHeap.shift();
        }
        return Math.max(...this.maxHeap.map(x => x[0]));
    }
    minimum(): number {
        while (this.minHeap.length && this.minHeap[0][0] !== this.time2price.get(this.minHeap[0][1])) {
            this.minHeap.shift();
        }
        return Math.min(...this.minHeap.map(x => x[0]));
    }
}

Complexity

  • ⏰ Time complexity: O(log n) per update/query (amortized, due to lazy deletion)
  • 🧺 Space complexity: O(n)