Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: For each element, find the next greater element in a circular array (−1 if none).

Problem: For each element, find the next greater element in a circular array (−1 if none).
def nge_circular(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_circular([1, 2, 1]), nge_circular([5, 4, 3, 2, 1]))
What is printed?
  1. A. [2, -1, -1] [-1, 5, 5, 5, 5]
  2. B. [2, -1, 2] [-1, -1, -1, -1, -1]
  3. C. [2, -1, 2] [-1, 5, 5, 5, 5]
  4. D. [2, 2, 2] [-1, 5, 5, 5, 5]

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

Walk the array twice (indices mod n) so elements near the end can find a greater value at the start; push indices only in the first pass. The last 1 wraps to 2; the maximum never finds anything. O(n).

More Coding Interview Problems questions

Exams that ask this topic