Data Structures & AlgorithmsModerateProduct-company MCQ pattern

In Python, a list q is used as a queue: items are added with q.append(x) and removed with q.pop(0). If n items pass through the queue, which statement is correct?

  1. A. append is O(n), so the cost is dominated by appends
  2. B. The total cost is O(n) because both operations are O(1)
  3. C. pop(0) is O(log n), so the total is O(n log n)
  4. D. The total cost is O(n²) because pop(0) shifts all remaining items; collections.deque.popleft() would make it O(n)

Correct answer: D. The total cost is O(n²) because pop(0) shifts all remaining items; collections.deque.popleft() would make it O(n)

A Python list is a dynamic array: pop(0) moves every remaining element one place left, which is O(n) each time. deque is a linked block structure with O(1) operations at both ends; append on a list is O(1) amortised.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic