ProgrammingHardCodeforces-style · placement coding round
Which statement about bisect.insort(a, x) on a plain Python list a is true?
- A. O(log n) because bisect finds the spot in logarithmic time
- B. Each insort is O(n) in the worst case, because later items are shifted to make room
- C. Each insort is O(1) amortised, like append
- 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
- What is printed? python import itertools print(list(itertools.accumulate([3, 1, 4], initial=10)))
- What is printed? python from itertools import groupby s = 'aabbaa' print([(k, len(list(g))) for k, g in groupby(s)])
- What is printed? python print(sorted(['b', 'A', 'a', 'B'], key=str.lower))
- What is printed? python nums = map(int, '1 2 3'.split()) a = list(nums) b = list(nums) print(a, b)
- What is printed? python print(1020 + 1 - 1020, float(1020 + 1) - float(1020))
- What is printed? python data = [('b', 2), ('a', 2), ('c', 1), ('a', 1)] print(sorted(sorted(data, key=lambda t: t[0]), key=lambda t: t[1]…