Data Structures & AlgorithmsVery hardProduct company OA
Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state = set of done tasks → (sessions, hours used in the last one)) versus first-fit in the given order and first-fit decreasing.
Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state = set of done tasks → (sessions, hours used in the last one)) versus first-fit in the given order and first-fit decreasing.
from functools import lru_cache
def sessions(tasks, T):
n = len(tasks)
@lru_cache(None)
def go(mask):
if mask == 0: return (0, 0)
best = (99, 0)
for i in range(n):
if mask >> i & 1:
s, used = go(mask ^ 1 << i)
cand = (s, used + tasks[i]) if used + tasks[i] <= T else (s + 1, tasks[i])
best = min(best, cand)
return best
s, used = go((1 << n) - 1)
return s + (used > 0)
def first_fit(tasks, T):
bins = []
for t in tasks:
for i, b in enumerate(bins):
if b + t <= T: bins[i] += t; break
else: bins.append(t)
return len(bins)
t = [3, 4, 5, 3, 2, 4, 3]
print(sessions(t, 8), first_fit(t, 8), first_fit(sorted(t, reverse=True), 8))What is printed?- A. 4 4 4
- B. 3 3 3
- C. 3 4 4
- D. 3 4 3
Correct answer: D. 3 4 3
The DP over 2ⁿ masks keeps, for each set of finished tasks, the lexicographically best (full sessions, load of the open session) – valid because a smaller open load never hurts. Total work 24 = 3 × 8, so 3 is a lower bound and it is achieved: (3, 5), (4, 4), (3, 3, 2). First fit in the given order opens a 4th session; sorting descending first happens to find 3 here, but neither heuristic is guaranteed optimal (bin packing is NP-hard), which is why n ≤ 14-type limits signal bitmask DP.
More Coding Interview Problems questions
- Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row…
- Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day…
- Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph…
- Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?). python…
- Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow)…
- Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k…