PPractick

DSA interview question

Stock Span

Hard · Data structures · Topics: stack, monotonic stack

The problem

A brokerage app shows, next to each day's closing price, its span: the number of consecutive days up to and including today on which the price was ≤ today's price. A span of 6 means the stock is at a six-day high. Walking backwards from each day is O(n²) on long rising runs. A stack of previous higher prices fixes that. Pop every earlier day whose price is ≤ today's (they're absorbed into today's span), and the remaining top is the previous strictly higher day. The span is the distance to it.

Example: [100, 80, 60, 70, 60, 75, 85] → [1, 1, 1, 2, 1, 4, 6].

Function signature

vector<int> calculateSpan(const vector<int>& price);

Test cases

InputOutputExplanation
[100, 80, 60, 70, 60, 75, 85][1, 1, 1, 2, 1, 4, 6]85 covers everything back to after 100
[10, 4, 5, 90, 120, 80][1, 1, 2, 4, 5, 1]
[5, 5, 5][1, 2, 3]Equal prices count (≤)
[3, 2, 1][1, 1, 1]
[1, 2, 3][1, 2, 3]

(Confirm: the span includes today; it counts consecutive previous days with price ≤ today's.)

How interviewers phrase it

Clarifying questions to ask

  1. Do equal prices count? (Yes: ≤.)
  2. Does the span include today? (Yes.)
  3. Offline array or online stream?

Follow-ups to expect

  1. "What does the span relate to?"
  2. "Why pop days with price ≤ today?"
  3. "Online version?"
  4. "Why O(n)?"
  5. "Which classic problem is this?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in