ProgrammingHardCodeforces-style · placement coding round

Which statement about bisect.insort(a, x) on a plain Python list a is true?

  1. A. O(log n) because bisect finds the spot in logarithmic time
  2. B. Each insort is O(n) in the worst case, because later items are shifted to make room
  3. C. Each insort is O(1) amortised, like append
  4. D. O(n log n) per insert because the list is re-sorted

Correct answer: B. Each insort is O(n) in the worst case, because later items are shifted to make room

bisect finds the position in O(log n), but inserting into a Python list moves the tail one slot, which costs O(n) in the worst case. A balanced tree or a sorted-container library avoids this cost.

More Python Programming questions

Exams that ask this topic