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})- A. 1
- B. 3
- C. 2
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer coins[4] = {9, 6, 5, 1} // sorted largest first Integer amt = 11, used = 0…
- What will be the output of the following pseudocode? Integer a[8] = {10, 9, 2, 5, 3, 7, 101, 18} Integer L[8], best = 0 for (each i from 0…
- What will be the output of the following pseudocode? (strings are indexed from 0) String x = "SUNDAY", y = "SATURDAY" Integer…
- What will be the output of the following pseudocode? Integer a[6] = {5, 5, 10, 100, 10, 5} Integer incl = 0, excl = 0, t for (each i from…
- An array of n elements is ALREADY sorted in increasing order. What is the time complexity of this pseudocode on it? for (each i from 1 to…
- What is the time complexity of the following pseudocode, as a function of n? Procedure f(Integer n) if (n <= 1) return end if for (each i…