ProgrammingModerateProduct-company MCQ pattern
Which operation is O(1) amortised in CPython?
- A. list.insert(0, x)
- B. list.append(x)
- C. str.replace on a long string
- D. list.pop(0)
Correct answer: B. list.append(x)
list.append adds at the end and reallocates in bulk, so the cost averages out to O(1). insert and pop at index 0 shift every element, which costs O(n).
More Python Programming questions
- What is printed? python from functools import lrucache @lrucache(maxsize=None) def f(a, b=0): return a + b f(1, 2) f(1, b=2) f(1)…
- What is printed? python from collections import OrderedDict od = OrderedDict() for k in ['a', 'b', 'c']: od[k] = ord(k) od.movetoend('a')…
- What is printed? python b = [3, 1, 2] a = b.sort() c = sorted(b, reverse=True) print(a, b, c)
- What is printed? python def kadane(a): best = cur = a[0] start = bestl = bestr = 0 for i in range(1, len(a)): if cur < 0: cur = a[i] start…
- What is printed? python def threesum(a): a = sorted(a) out = [] for i in range(len(a) - 2): if i and a[i] == a[i - 1]: continue l, r = i +…
- What is printed? python def distinct(s, t): dp = [1] + [0] len(t) for ch in s: for j in range(len(t), 0, -1): if t[j - 1] == ch: dp[j] +=…