~/problems / Range queries / Segment tree (+ lazy propagation)

Greenhouse: hottest sensor in a range

easy ~15 min

A long greenhouse has n temperature sensors in a row, numbered 0 .. n-1. Sensors report new readings all day, and the gardener often asks: "between sensor l and sensor r, which sensor is the hottest right now?" (so she knows where to open a vent).

Implement Greenhouse(temps), where temps[i] is sensor i's first reading, with:

  • report(i, temp) -> None: sensor i now reads temp.
  • hottest(l, r) -> int: the index of the sensor with the highest current reading among sensors l .. r (both inclusive). If several share the highest reading, return the smallest index.
g = Greenhouse([21, 25, 19, 25, 22])
g.hottest(0, 4)    # 1   (25 at sensors 1 and 3; the leftmost wins)
g.hottest(2, 4)    # 3
g.report(3, 18)
g.hottest(0, 4)    # 1
g.hottest(2, 4)    # 4   (22)
g.hottest(2, 2)    # 2

Constraints: 1 <= n <= 10**5, 0 <= l <= r < n, readings are integers in -50 .. 60, up to 10**5 calls in total. Scanning l .. r on every hottest is O(n) per call; both calls must be O(log n).

Show hint

build a segment tree whose nodes store the index of the hottest sensor in their range (or a pair like (temp, -index) so plain max breaks ties towards the left). Combine two children by comparing their winners; report fixes the leaf and its ancestors, and hottest combines the O(log n) nodes that exactly cover l .. r.

Topic: Segment tree (+ lazy propagation). Any associative range query with point or range updates in O(log n).

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc