Quant Memo
Coding/●●●●●

Stock span with a monotonic stack

Asked at DE Shaw, Jane Street

The "stock span" on a day is the number of consecutive days ending today (today included) on which the price was less than or equal to today's price.

prices = [100, 80, 60, 70, 60, 75, 85]
-> [1, 1, 1, 2, 1, 4, 6]

Return the span for every day. Aim for O(n)O(n); the day-by-day backward scan is O(n2)O(n^2).

Show a hint

When today's price is high, it "swallows" all the recent lower days at once. Which earlier day is the first one that can stop today's span, and can you jump straight to it?

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions