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[8] = {1, 3, -1, -3, 5, 3, 6, 7}, k = 3
Deque d = empty                // holds indices
for (each i from 0 to 7)
    if (d not empty AND front(d) <= i - k) popFront(d)
    while (d not empty AND a[back(d)] <= a[i]) popBack(d)
    pushBack(d, i)
    if (i >= k - 1) Print a[front(d)]
end for
  1. A. 3 3 5 5 6 6
  2. B. 3 -1 5 5 6 7
  3. C. 1 3 5 5 6 7
  4. D. 3 3 5 5 6 7

Correct answer: D. 3 3 5 5 6 7

The deque keeps indices of a decreasing run of values, so its front is the maximum of the current window of 3. Window maxima: [1 3 −1] 3, [3 −1 −3] 3, [−1 −3 5] 5, [−3 5 3] 5, [5 3 6] 6, [3 6 7] 7.

More Pseudocode and Code Tracing questions

Exams that ask this topic