Google questions

Temperature Monitor

GoogleMedium

A weather station reports integer temperature readings one at a time. A monitor keeps track of the n most recent readings, called the window, so its statistics can be read at any moment. The window counts readings, not time: it always holds the last n readings that were inserted, equal values included. Until n readings have arrived, the window holds all readings so far.

Part 1: Window statistics

Implement the TemperatureMonitor class:

  • TemperatureMonitor(n) creates a monitor whose window holds the n most recent readings.
  • insert(t) records the reading t and returns nothing.
  • moving_average() returns the average of the readings in the window as a float rounded to 6 decimal places.
  • max_temp() returns the largest reading in the window.

Both moving_average() and max_temp() must take O(1) time.

  1. Example 1
    init
    [3]
    operations
    [["insert",[10]],["moving_average",[]],["max_temp",[]],["insert",[20]],["moving_average",[]],["max_temp",[]],["insert",[15]],["moving_average",[]],["max_temp",[]],["insert",[5]],["moving_average",[]],["max_temp",[]],["insert",[1]],["moving_average",[]],["max_temp",[]]]
    Output
    [null,10,10,null,15,20,null,15,20,null,13.333333,20,null,7,15]

    Why: After 10, 20 and 15 the window is full: the average is 15 and the maximum is 20. Inserting 5 drops 10, so the window is 20, 15, 5 (average 13.333333, maximum 20). Inserting 1 drops 20, so the window is 15, 5, 1 (average 7, maximum 15).

Constraints

  • 1 <= n <= 10^5
  • -10^6 <= t <= 10^6
  • 1 <= len(operations) <= 2 * 10^5
  • moving_average and max_temp are only called after at least one insert
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Temperature Monitor: Google interview question | LoopCoach