Data Structures & AlgorithmsVery hardGATE CS · TCS NQT · Product Company SDE

Using a monotonic (decreasing) stack to find, for each element of [32, 3, 22, 30, 36, 26, 11, 9], the next element to its right that is strictly greater (or -1 if none), what is the resulting array?

  1. A. [36, 30, 22, 36, -1, -1, -1, -1]
  2. B. [36, 22, 30, 36, -1, -1, -1, -1]
  3. C. [-1, -1, 3, 22, 30, 22, 3, 3]
  4. D. [-1, 32, 32, 32, -1, 36, 26, 11]

Correct answer: B. [36, 22, 30, 36, -1, -1, -1, -1]

Scan left to right keeping a stack of indices whose values still need a next-greater; pop and record whenever the current value exceeds the stack top: [36, 22, 30, 36, -1, -1, -1, -1]

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

Exams that ask this topic