ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (Arrays are indexed from 0)

What will be the output of the following pseudocode? (Arrays are indexed from 0)
Integer a[6] = {4, 5, 2, 25, 7, 8}, res[6]
Stack st = empty            // holds indices
for (each i from 0 to 5)
    while (st not empty AND a[top(st)] < a[i])
        res[pop(st)] = a[i]
    end while
    push(st, i)
end for
while (st not empty)
    res[pop(st)] = -1
end while
Print res[0], res[2], res[4]
  1. A. 5 5 8
  2. B. 25 25 8
  3. C. 5 25 -1
  4. D. 5 25 8

Correct answer: D. 5 25 8

The stack finds each element's next greater element to the right: 4 → 5, 2 → 25 (5 is to its left), 7 → 8. Output 5 25 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic