ProgrammingVery hardAmazon OA · Goldman Sachs OA
What is the time complexity of the following pseudocode on an array of n elements?
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 not empty AND top(st) < a[i])
pop(st)
end while
push(st, a[i])
end for- A. O(n²)
- B. O(n)
- C. O(n log n)
- D. O(log n)
Correct answer: B. O(n)
Although the while loop sits inside the for loop, every element is pushed once and popped at most once, so the total number of pops over the whole run is at most n. Amortised, the work is O(n).
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? (c ? x : y evaluates x if c is true, otherwise y) Integer marks[6] = {92, 75, 60, 88…
- What will be the output of the following pseudocode? (continue in a do-while loop goes straight to the while test) Integer x = 1, c = 0 do…
- What will be the output of the following pseudocode? (s[i] - '0' turns a digit character into its value; strings are indexed from 0)…
- What will be the output of the following pseudocode? (+ joins strings) Integer count = 0 String third = "" Procedure gen(String s, Integer…
- What will be the output of the following pseudocode? Integer s = 0 for (each i from 1 to 49) if (i mod 3 == 0 OR i mod 5 == 0) s = s + i…
- What will be the output of the following pseudocode? (| is OR, & is AND, << and >> are shifts) Integer c = 0, r, x for (each n from 1 to…