ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def nge(a):
    st, res = [], [-1] * len(a)
    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. [4, 4, 4, -1, -1]
  2. B. [4, 2, 4, -1, -1]
  3. C. [4, 2, 4, 4, -1]
  4. D. [2, 4, 4, -1, -1]

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

A monotonic stack finds each element's next greater value. 2 is followed by 4, the 1 is followed by 2, the second 2 is followed by 4, and 4 and 3 have no greater value to their right.

More Python Programming questions

Exams that ask this topic