Data Structures & AlgorithmsVery hardCodeforces Div2 C · GATE CS

For the array [4, 2, 5, 3, 1, 6, 0], a 'next greater element' routine returns for each index the value of the next strictly larger element to its right, or −1 if none. A buggy version scans forward for a larger element, and if none is found it returns a[i+1] whenever a[i+1] < a[i]. At which 0-based index does the buggy output first differ from the correct output? Answer −1 if they agree everywhere.

  1. A. 6
  2. B. 5
  3. C. 4
  4. D. 7

Correct answer: B. 5

The buggy fallback invents a value when no larger element exists, so the first divergence happens at an index whose next greater element does not exist. A correct monotone stack leaves −1 there.

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

Exams that ask this topic