1. Count today
Every price spans at least itself.
let span = 1Typorithm · medium
Step 1 of 8 · intro card
Monotonic Stack
A decreasing stack of [price, span] pairs; today absorbs all not-greater days, summing their spans in O(1) amortized.
The span is how many consecutive prior days, up to today, had a price at or below today's.
A decreasing stack stores [price, span] pairs; today pops and absorbs every day with a price not exceeding it.
Folding in each popped span avoids recounting, giving amortized O(1) per call in a streaming setting.
Stack holds [price, span] pairs.
Absorb days with price <= today.
Sum their spans instead of recounting.
class StockSpanner {
constructor() {
this.stack = [];
}
next(price) {
let span = 1;
while (this.stack.length > 0 && this.stack[this.stack.length - 1][0] <= price) {
span += this.stack.pop()[1];
}
this.stack.push([price, span]);
return span;
}
}Connect each part of the code to the concept before you type.
Every price spans at least itself.
let span = 1Days with price <= today are subsumed by today's span.
while (this.stack.length > 0 && this.stack[this.stack.length - 1][0] <= price) {Pop each absorbed day and fold in its precomputed span.
span += this.stack.pop()[1]Push the price with its computed span for future calls.
this.stack.push([price, span])Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.