Data Structures & AlgorithmsVery hardProduct company OA
Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?
Total element copies when a dynamic array is filled with 100 items under three growth rules (cost, final capacity). What is printed?
def copies(n, grow):
cap, size, cost = 1, 0, 0
for _ in range(n):
if size == cap:
cost += size
cap = grow(cap)
size += 1
return cost, cap
print(copies(100, lambda c: 2 * c), copies(100, lambda c: c + c // 2 + 1), copies(100, lambda c: c + 10))- A. (127, 128) (196, 139) (460, 101)
- B. (127, 128) (261, 139) (460, 101)
- C. (99, 128) (261, 139) (4950, 101)
- D. (127, 128) (261, 139) (500, 110)
Correct answer: B. (127, 128) (261, 139) (460, 101)
A copy of all current items happens whenever size reaches capacity. Doubling: 1+2+4+…+64 = 127, about n – O(1) amortised. Growth by ×1.5 (+1) still copies a geometric series, 261 here, a larger constant but still O(1) amortised. Growing by a constant 10 copies 1, 11, 21, …, 91 = 460 for only 100 items, and in general Θ(n²/10) – O(n) amortised per insert. A constant increment is the trap even though it wastes the least memory.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A 'last position ≤ x' binary search with the loop capped at 50 iterations, returning (lo, iterations). What is printed? python def…
- Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes…
- Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed? python from collections…
- Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking…
- Probe-sequence coverage for open addressing: how many distinct slots can the offsets i² (quadratic) and i(i+1)/2 (triangular) reach in…
- An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order? python from…