Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day's price.

Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day'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([31, 27, 14, 21, 30, 22]))
What is printed?
  1. A. [1, 1, 1, 2, 4, 1]
  2. B. [1, 1, 1, 2, 3, 1]
  3. C. [1, 1, 1, 2, 4, 2]
  4. D. [1, 2, 3, 4, 5, 6]

Correct answer: A. [1, 1, 1, 2, 4, 1]

The stack keeps indices of a decreasing run of prices. On 30, the prices 21, 14 and 27 are all ≤ 30 and popped, leaving 31 at index 0, so the span is 4 − 0 = 4. On 22, the previous price 30 is higher, so the span is 1.

More Coding Interview Problems questions

Exams that ask this topic