ProgrammingVery hardTCS NQT · Accenture

The stack-based procedure below computes, for each index i of a = [4, 2, 6, 1, 5], the index of the next greater element to its right (or -1 if there is none), and then prints the sum of these indices. What is printed?

The stack-based procedure below computes, for each index i of a = [4, 2, 6, 1, 5], the index of the next greater element to its right (or -1 if there is none), and then prints the sum of these indices. What is printed?
stack = empty; nxt = [-1] * n
for i = 0 to n - 1
    while stack not empty and a[top] < a[i]: nxt[top] = i; pop
    push i
end for
Print sum of nxt
  1. A. 5
  2. B. 15
  3. C. 6
  4. D. 0

Correct answer: C. 6

The next greater indices are 2, 2, -1, 4 and -1, so the sum is 6. Using the wrong comparison gives 5, storing values instead of indices gives 15, and forgetting to push indices onto the stack gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic