Data Structures & AlgorithmsHardGATE CS · DSA

For each element of [23, 12, 7, 21, 25, 8, 13, 1], find the next greater element to its RIGHT (−1 if none), using a monotonic stack. What is the output?

  1. A. [−1, 23, 12, 23, −1, 25, 25, 13]
  2. B. [25, 21, 21, 25, −1, 13, −1, −1]
  3. C. [25, 25, 25, 25, −1, 13, −1, −1]
  4. D. [−1, −1, 21, 25, −1, 13, −1, −1]

Correct answer: B. [25, 21, 21, 25, −1, 13, −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