ProgrammingHardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer a[7] = {4, 5, 2, 10, 8, 6, 9}
Stack st = empty
for (each i from 0 to 6)
while (st not empty AND top(st) >= a[i])
pop(st)
end while
if (st is empty) Print -1 else Print top(st)
push(st, a[i])
end for- A. -1 4 4 2 8 6 6
- B. 4 2 -1 8 6 -1 -1
- C. -1 -1 -1 2 2 2 6
- D. -1 4 -1 2 2 2 6
Correct answer: D. -1 4 -1 2 2 2 6
For each element the stack gives the nearest smaller value to its left: 4 → none, 5 → 4, 2 → none, 10 → 2, 8 → 2, 6 → 2, 9 → 6. Output -1 4 -1 2 2 2 6.
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? (+ joins strings) Queue q = {"1"} Integer k = 0 String s while (k < 6) s = dequeue(q)…
- What will be the output of the following pseudocode? Integer a[6] = {1, 2, 1, 3, 2, 1} Map cnt = empty Integer pairs = 0 for (each i from…
- What will be the output of the following pseudocode? Integer move = 0 Procedure hanoi(Integer n, Char a, Char b, Char c) if (n == 0)…
- What is the time complexity of the following pseudocode, as a function of n? for (each i from 1 to n) j = 1 while (j < i) j = j 2 end…
- What is the time complexity of the following pseudocode on an array of n elements? Stack st = empty for (each i from 0 to n - 1) while (st…
- What will be the output of the following pseudocode? (c ? x : y evaluates x if c is true, otherwise y) Integer marks[6] = {92, 75, 60, 88…