ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode?

What will be the output of the following pseudocode?
Function possible(Integer out[5])
    Stack st = empty
    Integer next = 1
    for (each i from 0 to 4)
        while (next <= 5 AND (st is empty OR top(st) != out[i]))
            push(st, next)
            next = next + 1
        end while
        if (top(st) != out[i])
            return 0
        end if
        pop(st)
    end for
    return 1
End Function
Print possible({4, 5, 3, 2, 1}) + possible({4, 3, 5, 1, 2}) + possible({3, 2, 4, 1, 5}) + possible({5, 1, 2, 3, 4})
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

The function checks whether pushing 1 to 5 in order and popping at the right moments can give each output. 4 5 3 2 1: yes. 4 3 5 1 2: after 4 3 5, the stack holds 1, 2 with 2 on top, so 1 cannot come next: no. 3 2 4 1 5: yes. 5 1 2 3 4: no (4 is on top after 5). Total 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic