Data Structures & AlgorithmsVery hardProduct company OA

Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed?

Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). 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([3, 8, 4, 1, 2, 8, 0]))
  1. A. [8, -1, 8, 2, 8, -1, -1]
  2. B. [8, -1, 8, 2, 8, 8, 3]
  3. C. [8, 8, 8, 2, 8, -1, 3]
  4. D. [8, -1, 8, 2, 8, -1, 3]

Correct answer: D. [8, -1, 8, 2, 8, -1, 3]

The second lap lets elements near the end find a larger value at the front. 0 at the end wraps around to 3. Both 8s are the maximum, and 'greater' is strict, so neither finds anything (−1); treating equal as greater gives the option with an 8 for index 5. Each index is pushed once and popped at most once, so 2n iterations total – O(n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic