TRT
Sign in
mediumAdvancedLeetCode#hash map plus ordered multiset#heaps with lazy deletion

Stock price fluctuation

Handle out-of-order and corrected price updates while reporting the latest, highest and lowest prices, with a hash map plus an ordered structure.

The Runtime Theory Team1 min read
Taught inChoosing an ordered structurePro — members onlySorted arrays, heaps, balanced trees, skip lists and B-trees all keep data in order, with very different costs. The right choice follows from which operations you need, how often the data changes, and what your language provides.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inupdate(1, 10), update(2, 5), current(), maximum(), update(1, 3), maximum(), update(4, 2), minimum()

out[5, 10, 5, 2]

inupdate(1, 7), update(1, 3), maximum(), minimum()

out[3, 3]

inupdate(5, 1), update(2, 9), current()

out[1]

Price records arrive as (timestamp, price), possibly out of order, and a later record for an existing timestamp corrects the earlier one. Implement update, current (the price at the latest timestamp), maximum and minimum over the current records. The expected output lists the results of current, maximum and minimum.

Before you code

A correction must remove the old price from whatever answers maximum and minimum. Which structure knows the old price, and which one can remove it?

Hints

  1. Keep a hash map from timestamp to price, and the largest timestamp seen.
  2. Keep prices in an ordered multiset: on a correction, remove the old price and add the new one. Maximum and minimum are its ends.
  3. Alternatively, keep a max-heap and a min-heap of (price, timestamp). When reading the top, discard entries whose price no longer matches the hash map.

Production & complexity notes

When solving Stock price fluctuation on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Choosing an ordered structure to reinforce the underlying pattern.

What it practices

Combining a hash map with an ordered structure, from Choosing an ordered structure.

Not started

Sign in to save your learning progress.

Sign in to save