Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price.

Problem: Compute the stock span: for each day, the number of consecutive days up to today with price ≤ today's price.
def spans(p):
    st, out = [], []
    for i, x in enumerate(p):
        while st and p[st[-1]] <= x: st.pop()
        out.append(i + 1 if not st else i - st[-1])
        st.append(i)
    return out
print(spans([100, 80, 60, 70, 60, 75, 85]))
What is printed?
  1. A. [1, 1, 1, 2, 1, 3, 6]
  2. B. [1, 1, 1, 2, 1, 4, 5]
  3. C. [1, 1, 1, 2, 1, 4, 6]
  4. D. [1, 2, 3, 4, 5, 6, 7]

Correct answer: C. [1, 1, 1, 2, 1, 4, 6]

Pop all previous days with price ≤ today; the remaining top is the previous greater day, and the span is the distance to it. 75 covers 60, 70, 60, 75 → 4; 85 covers back to just after 100 → 6. O(n) amortised.

More Coding Interview Problems questions

Exams that ask this topic