ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def span(p):
    st, out = [], []
    for i, x in enumerate(p):
        while st and p[st[-1]] <= x:
            st.pop()
        out.append(i - (st[-1] if st else -1))
        st.append(i)
    return out
print(span([100, 80, 60, 70, 60, 75, 85]))
  1. A. [1, 1, 1, 2, 1, 4, 6]
  2. B. [1, 1, 1, 2, 1, 3, 5]
  3. C. [1, 1, 1, 2, 1, 4, 7]
  4. D. [1, 1, 2, 2, 1, 4, 6]

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

The stack holds indices of earlier prices that are still higher. Each span is the distance to the nearest higher earlier price, and 85 reaches back to index 0 for a span of 6.

More Python Programming questions

Exams that ask this topic