KatInterview

Fewest Cabinets for Two-Resource Jobs

Dynamic ProgrammingAuto-graded · 23 test cases
HardAuto-gradedDynamic Programmingbin-packingbacktrackingbitmask

Last updated

Group jobs with two resource demands into the fewest identical cabinets, using exact search with symmetry breaking and pruning (2D vector bin packing).

A data center must host a set of jobs. Job i needs jobs[i][0] units of the first resource and jobs[i][1] units of the second resource. Jobs are stored in identical cabinets, and each cabinet offers cap_a units of the first resource and cap_b units of the second.

Each job must be placed entirely inside one cabinet; it cannot be split. A cabinet may hold any number of jobs, provided that for each resource separately, the total demand of the jobs in that cabinet is at most the cabinet's capacity for that resource.

Return the smallest number of cabinets that can hold every job.

Special cases

  • If there are no jobs, return 0.
  • If some single job exceeds cap_a in the first resource or cap_b in the second resource, no valid placement exists, so return -1.
  • Jobs with zero demand in one or both resources are allowed and are placed like any other job.

Parameters

  • jobs: a list of [need_a, need_b] pairs.
  • cap_a: the capacity of one cabinet for the first resource.
  • cap_b: the capacity of one cabinet for the second resource.

Returns an integer: the minimum number of cabinets, or -1 if impossible.

Constraints

  • 0 <= len(jobs) <= 20 (an exact search is expected, so the job count is small).
  • Every demand and both capacities are non-negative integers.
  • Jobs may be grouped in any way and in any order.
  • Identical jobs may appear multiple times.

Examples

Example 1

Input: min_cabinets([[2, 2], [3, 3], [4, 1], [1, 4]], 5, 5)

Output: 2

Example 2

Input: min_cabinets([[2, 2], [2, 2], [2, 2]], 4, 4)

Output: 2

Example 3

Input: min_cabinets([[6, 1], [1, 6]], 5, 5)

Output: -1

Hints

Hint 1

This is NP-hard in general, so with about 20 jobs aim for a well-pruned exhaustive search rather than a polynomial algorithm.

Hint 2

Process jobs one at a time, placing each into an already-open cabinet where it fits or into one new cabinet. Placing the largest jobs first makes dead ends show up early.

Hint 3

Prune hard: stop any branch whose cabinet count already reaches the best answer found, and skip open cabinets whose current load is identical to one you already tried for this job.