AlgoMaster Logo
AlgoMasterCalculate Counter Rates Across Resetsmedium

Calculate Counter Rates Across Resets

medium

A counter normally increases, but process restarts reset it to zero. Treating the resulting negative delta as real traffic produces an incorrect rate.

Design a CounterRateCalculator class:

  • CounterRateCalculator() creates a stateless calculator.
  • int totalIncrease(int[] values) returns the counter increase represented by the samples.
  • double averageRate(int[] timestamps, int[] values) returns increase per time unit, rounded to 5 decimal places.

The first value is a baseline. For every later sample:

  • If current >= previous, add current - previous.
  • If current < previous, assume a reset to zero occurred and add current.

For averageRate, divide the total increase by timestamps[last] - timestamps[0]. This exercise uses a simplified reset model and does not perform Prometheus boundary extrapolation.

Example 1:

Input:

Output:

Explanation: The increases are 30 and 30. Sixty events over twenty seconds gives 3 events per second.

Example 2:

Input:

Output:

Explanation: The decrease from 120 to 10 is a reset. The new counter has already recorded 10 events, so total increase is 30 + 10 + 30 = 70.

Constraints

  • 2 <= values.length <= 10^5
  • 0 <= values[i] <= 10^6
  • For averageRate, timestamps.length == values.length.
  • Timestamps are strictly increasing non-negative integers.
  • Total increase fits in a signed 32-bit integer.
  • Round only the final average rate; answers are accepted within 10^-5.
  • At most 100 total method calls are made.
Hints

Loading...
CallReturns
new CounterRateCalculator()null
totalIncrease([100,130,160])60
averageRate([0,10,20], [100,130,160])3

The counter rises by 30 twice, producing 60 events over 20 seconds, or 3 per second.

Run checks these cases. Submit also runs a larger hidden set.