MediumHash TableDesignHeapData StreamUpdated Sep 2026

2034. Stock Price Fluctuation

Asked at Atlassian

Difficulty

Medium

Time

O(log n) per update, O(1) for cu

Space

O(n)

Pattern

Hash Table

Companies

1

Problem

Design a class StockPrice that keeps track of a stock's price over time. Records arrive one at a time, and they may arrive out of order. A record can also be wrong: a later record with the same timestamp replaces the earlier price for that timestamp.

Implement these methods:

  • update(timestamp, price) — record the price at that timestamp. If a record for that timestamp already exists, overwrite it.
  • current() — return the price at the largest timestamp seen so far.
  • maximum() — return the largest price among all current records.
  • minimum() — return the smallest price among all current records.

Only the newest price for each timestamp counts. If a timestamp is overwritten, its old price must no longer affect maximum() or minimum().

Out-of-order records with corrections

records1:102:5After update(1,10) and update(2,5): current = 5,maximum = 10records1:32:54:2update(1,3) overwrites timestamp 1, then update(4,2)adds timestamp 4: minimum = 2
Records arrive in any order, and a later record for the same timestamp replaces the old price.

Constraints

  • ●1 <= timestamp, price <= 10^9
  • ●At most 10^5 calls in total to update, current, maximum, and minimum
  • ●current, maximum, and minimum are only called after at least one update

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]
WhyAfter update(1,10) and update(2,5) the records are {1:10, 2:5}. current() returns 5 because timestamp 2 is the newest. maximum() returns 10. Then update(1,3) overwrites timestamp 1, so the records become {1:3, 2:5} and maximum() drops to 5. Finally update(4,2) adds timestamp 4, and minimum() returns

Asked At

1 companies
CompanyDifficulty
AtlassianMediumView all Atlassian questions →

How to Think About It

1

Naive approach: store all (timestamp, price) pairs in a list. current() is O(1) (last element). maximum() and minimum() scan the entire list each time: O(n). This is too slow if maximum()/minimum() are called frequently.

2

Better: use a hash map (dictionary) mapping timestamp to price for O(1) updates and lookups. For max/min, maintain two heaps: a max-heap for maximum and a min-heap for minimum. This gives O(1) current, O(log n) update, O(1) amortized max/min.

3

The problem: heaps do not support efficient deletion of arbitrary elements. When you update a price at an existing timestamp, the old price is still in the heap. Solution: lazy deletion. Mark the old entry as stale in the hash map. When popping from the heap, skip entries where the hash map value does not match the heap top.

4

Data structures:

  • price_map: dict[timestamp] -> price for O(1) lookups.
  • max_heap: stores (-price, timestamp) for max price (negate for max-heap in Python).
  • min_heap: stores (price, timestamp) for min price.
  • latest_timestamp: tracks the most recent timestamp for current().
5

Lazy deletion example: timestamp 3 initially has price 100. Heap has (100, 3). Update timestamp 3 to price 50. Now price_map[3] = 50, but heap still has (100, 3). When you pop (100, 3) from min-heap, check price_map[3] == 100? No (it's 50). Discard and pop again.

6

Complexity: update() is O(log n) (two heap pushes). current() is O(1). maximum() and minimum() are O(log n) amortized (popping stale entries). Total space: O(n).

Optimal Approach

Maintain a hash map (price_map) mapping timestamp to price, a max-heap (max_heap) storing (-price, timestamp), and a min-heap (min_heap) storing (price, timestamp). Also track latest_timestamp.

update(timestamp, price):

  • Store price_map[timestamp] = price.
  • Push (-price, timestamp) onto max_heap.
  • Push (price, timestamp) onto min_heap.
  • Update latest_timestamp if timestamp is newer.

current():

  • Return price_map[latest_timestamp].

maximum():

  • Peek at max_heap[0]. While price_map[heap_top.timestamp] != -heap_top.price, pop (stale entry). Return -max_heap[0][0].

minimum():

  • Same lazy deletion logic on min_heap. Return min_heap[0][0].

Walkthrough: update(1, 10), update(2, 5), update(1, 20).

  • price_map = {1: 20, 2: 5}. Heaps have stale (10, 1).
  • maximum(): heap top is (-10, 1). price_map[1] is 20, not 10. Pop. Next is (-20, 1). price_map[1] is 20 = -(-20). Return 20.
  • minimum(): heap top is (5, 2). price_map[2] is 5. Return 5.

Time: O(log n) update, O(1) current, O(log n) amortized max/min. Space: O(n).

Hash map plus two lazy heaps

price_mapabtsprice11025After update(1,10) and update(2,5), the map stores thecurrent price for each timestamp.min_heap(5,2)(10,1)← topThe min-heap top (5,2) matches the map, so minimum()returns 5.update(1,3): map[1]=3push (-3,1) and (3,1)old (10,1) is now stalemaximum(): pop stale topsThe old price for timestamp 1 stays in the heaps butis skipped because the map disagrees.stale if price_map[ts] != heap_pricepop stale tops before answeringcurrent() = price_map[latest_ts]
The map holds the truth; the heaps hold candidates, and stale tops are popped when seen.
ComplexityTime O(log n) per update, O(1) for cuSpace O(n)Each update pushes onto two heaps, and stale heap entries are removed lazily, so each entry is popped at most once.

What Trips People Up in Real Interviews

1

Forgetting that updating the same timestamp overwrites the old price. The heap still contains the old (price, timestamp) pair. Without lazy deletion, you would return stale max/min values.

2

Using a TreeMap / SortedDict for max/min. While this works (O(log n) for max/min), heaps are more commonly expected in interviews and the lazy deletion pattern is a valuable signal.

3

Not tracking the latest timestamp for current(). If you only use heaps, you cannot efficiently get the latest price. You need either a hash map or a separate variable.

4

Pushing duplicate entries into the heap without lazy deletion. Do NOT try to remove old entries from the heap — it is O(n). Instead, push new entries and skip stale ones when popping.

5

Forgetting that Python's heapq is a min-heap. For a max-heap, negate the price: push (-price, timestamp) and negate again when reading back.

Solution Code

O(log n) per update, O(1) for cu time
import heapq

class StockPrice:

    def __init__(self):
        self.price_map = {}
        self.max_heap = []
        self.min_heap = []
        self.latest_timestamp = 0

    def update(self, timestamp: int, price: int) -> None:
        self.price_map[timestamp] = price
        heapq.heappush(self.max_heap, (-price, timestamp))
        heapq.heappush(self.min_heap, (price, timestamp))
        self.latest_timestamp = max(self.latest_timestamp, timestamp)

    def current(self) -> int:
        return self.price_map[self.latest_timestamp]

    def maximum(self) -> int:
        while self.max_heap:
            price, ts = self.max_heap[0]
            if self.price_map.get(ts) == -price:
                return -price
            heapq.heappop(self.max_heap)
        return -1

    def minimum(self) -> int:
        while self.min_heap:
            price, ts = self.min_heap[0]
            if self.price_map.get(ts) == price:
                return price
            heapq.heappop(self.min_heap)
        return -1

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Stock Price Fluctuation problem?

Design a data structure that tracks stock prices over time, supporting three operations: `update(timestamp, price)` to record a new price, `current()` to return the latest price, and `maximum()` / `minimum()` to return the highest and lowest prices recorded. Prices can be updated at the same timestamp, overwriting the previous value.

How do you solve Stock Price Fluctuation?

The optimal approach runs in O(log n) per update, O(1) for cu time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Stock Price Fluctuation?

Stock Price Fluctuation is asked at Atlassian. It is a medium difficulty problem.

What are common mistakes on Stock Price Fluctuation?
  • Forgetting that updating the same timestamp overwrites the old price. The heap still contains the old (price, timestamp) pair. Without lazy deletion, you would return stale max/min values.
  • Using a `TreeMap` / `SortedDict` for max/min. While this works (`O(log n)` for max/min), heaps are more commonly expected in interviews and the lazy deletion pattern is a valuable signal.
  • Not tracking the latest timestamp for `current()`. If you only use heaps, you cannot efficiently get the latest price. You need either a `hash map` or a separate variable.
  • Pushing duplicate entries into the heap without lazy deletion. Do NOT try to remove old entries from the heap — it is `O(n)`. Instead, push new entries and skip stale ones when popping.
  • Forgetting that Python's `heapq` is a min-heap. For a max-heap, negate the price: push `(-price, timestamp)` and negate again when reading back.