ProgrammingHardCognizant GenC · TCS NQT

What is printed?

What is printed?
def nge(a):
    res = [-1] * len(a)
    st = []
    for i, x in enumerate(a):
        while st and a[st[-1]] < x:
            res[st.pop()] = x
        st.append(i)
    return res
print(nge([2, 1, 2, 4, 3]))
  1. A. [-1, 2, 4, 4, -1]
  2. B. [2, 2, 4, -1, -1]
  3. C. [4, 2, 4, -1, -1]
  4. D. [4, 4, 4, -1, -1]

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

The stack holds indices still waiting for a larger value. When a larger value arrives, it pops those indices and records it, so index 0 gets 4 and index 1 gets 2.

More Python Programming questions

Exams that ask this topic