Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (next greater element to the right, −1 if none)

What is printed? (next greater element to the right, −1 if none)
a = [4, 5, 2, 25, 7, 8]
res, st = [-1] * len(a), []
for i in range(len(a) - 1, -1, -1):
    while st and st[-1] <= a[i]: st.pop()
    res[i] = st[-1] if st else -1
    st.append(a[i])
print(res)
  1. A. [5, 25, 25, -1, 8, -1]
  2. B. [5, 25, 25, -1, 8, 8]
  3. C. [5, 25, 7, -1, 8, -1]
  4. D. [5, 5, 25, -1, 8, -1]

Correct answer: A. [5, 25, 25, -1, 8, -1]

Scanning from the right, the stack keeps candidates in decreasing order; smaller or equal values are popped because they can never be the answer for anything further left. 2's next greater is 25 (not 7, which is further right). O(n).

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

Exams that ask this topic