Data Structures & AlgorithmsHardGATE CS · DSA

For each element of [16, 4, 2, 19, 10, 6, 29, 9], find the next greater element to its RIGHT (−1 if none), using a monotonic stack. What is the output?

  1. A. [19, 19, 19, 29, 29, 29, −1, −1]
  2. B. [−1, 16, 4, −1, 19, 10, −1, 29]
  3. C. [29, 29, 29, 29, 29, 29, −1, −1]
  4. D. [−1, −1, 19, −1, −1, 29, −1, −1]

Correct answer: A. [19, 19, 19, 29, 29, 29, −1, −1]

Scan left to right keeping a decreasing stack of indices; when a larger value arrives it resolves every smaller element on the stack. The 'first larger value to the right' is needed — not the largest, and not just the immediate neighbour.

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

Exams that ask this topic