DSA interview question
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].
vector<int> calculateSpan(const vector<int>& price);
| Input | Output | Explanation |
|---|---|---|
[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.)
next(price) returns today's span.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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in