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?
  1. A. 4 4 4
  2. B. 3 3 3
  3. C. 3 4 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

Exams that ask this topic