ProgrammingHardAmazon OA · Flipkart coding round

A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?

  1. A. O(n)
  2. B. O(n log n)
  3. C. O(n^3)
  4. D. O(n^2)

Correct answer: D. O(n^2)

Each pop(0) shifts all the remaining items one slot left, so the total work is about n^2/2 moves. Using collections.deque with popleft avoids this and costs O(n) in total.

More Python Programming questions

Exams that ask this topic