Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag. Binary search on the answer: a bag of b needs (b − 1) // cap splits.
Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most `ops` operations, minimise the largest bag. Binary search on the answer: a bag of b needs (b − 1) // cap splits.
def min_penalty(bags, ops):
lo, hi = 1, max(bags)
while lo < hi:
mid = (lo + hi) // 2
if sum((b - 1) // mid for b in bags) <= ops: hi = mid
else: lo = mid + 1
return lo
print(min_penalty([9, 4, 7], 3), min_penalty([20], 4), min_penalty([3, 3, 3], 0))What is printed?- A. 4 4 1
- B. 4 4 3
- C. 3 4 3
- D. 4 5 3
Correct answer: B. 4 4 3
To make every bag ≤ cap, a bag of b balls must become ⌈b / cap⌉ bags, i.e. (b − 1) // cap splits; feasibility is monotone in cap. cap = 4: 2 + 0 + 1 = 3 ≤ 3 ✓; cap = 3: 2 + 1 + 2 = 5 ✗ → 4. [20] with 4 splits → 5 bags of 4. Halving the biggest bag each time (a heap greedy) is wrong: [9] with 2 splits goes 9 → 5 + 4 → 3 + 2 + 4 (max 4), while 3 + 3 + 3 achieves 3. O(n log max).
More Coding Interview Problems questions
- Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move. python moves = [] def hanoi(n, a, b, c): if n ==…
- Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by…
- Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth). python def…
- Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1). python…
- Problem: Trace the output of a recursive function that prints before and after its recursive call. python def walk(n): if n == 0: return…
- Problem: Sum the values of all LEFT leaves (leaves that are the left child of their parent). Trees are built from a level-order list by…