Data Structures & AlgorithmsHardProduct Company SDE · stack round

Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from the start).

Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from the start).
def nge(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([1, 2, 1]))
  1. A. [2, -1, 2]
  2. B. [2, -1, -1]
  3. C. [2, 2, -1]
  4. D. [1, 2, 2]

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

Index 0 finds 2, index 1 has no larger value anywhere, and index 2 wraps around to find 2. Stopping the scan at n instead of 2n produces the trap [2, -1, -1].

More Coding Interview Problems questions

Exams that ask this topic