Problem 221138 · medium · Level 02 Linear Data Structures

Rising Streak Counter

stacks · monotonic stack · class design

Design a class StreakCounter that receives one value at a time. When a value x arrives, its streak is the number of consecutive values, counting backwards from x itself, that are less than or equal to x (so the streak is at least 1).

  • StreakCounter(): create an empty counter.
  • add(x): record x and return its streak.

Examples

Input:  ops  = ["StreakCounter", "add", "add", "add", "add", "add", "add", "add"]
        args = [[], [100], [80], [60], [70], [60], [75], [85]]
Output: [None, 1, 1, 1, 2, 1, 4, 6]
Explanation: 75 is preceded by 60, 70, 60 (all <= 75) and then 80 stops the streak, so its streak is 4.

Constraints

  • At most 10**4 calls to add
  • Target: amortised O(1) per call (rescanning previous values is too slow)

Goals

  • Collapse dominated entries into a single stack element with a combined count
  • Achieve amortised O(1) per call on a streaming input
Starting Python…