ProgrammingVery hardAmazon OA · Flipkart coding round

What is printed?

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

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

Looping twice over the array lets the last 1 find the 2 that wraps around. The first pass pushes indices, and the second pass only resolves the ones still waiting.

More Python Programming questions

Exams that ask this topic