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
  1. A. O(n²)
  2. B. O(n)
  3. C. O(n log n)
  4. 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).

More Pseudocode and Code Tracing questions

Exams that ask this topic