progress

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

Greenhouse: hottest sensor in a range

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~20 min

A greenhouse has n temperature sensors in a row. Readings change all day, and the gardener asks: "between sensors l and r, which one is hottest right now?" (to open the right vent).

Implement Greenhouse(temps) with:

  • report(i, temp): sensor i now reads temp.
  • hottest(l, r) -> int: the index of the hottest sensor in l .. r (inclusive); ties go to 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

Up to 10**5 sensors (readings -50..60) and 10**5 calls.

⭐ Bonus: scanning l .. r per call still passes; a speed test with 10**5 calls on 10**5 sensors earns a star at O(log n) per call.

Show hint

a segment tree whose nodes store the winning index of their range (or (temp, -index) so max breaks ties leftwards). report fixes a leaf and its ancestors; hottest combines the O(log n) nodes covering 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