Minimum Racks for Dual-Resource Machine Packing
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A data center needs to host a batch of servers on uniform hardware racks. Each rack supplies at most A units of a primary resource (such as CPU cores) and B units of a secondary resource (such as memory). You are given machines, where machines[i] = [x_i, y_i] denotes the primary and secondary resource demands of server i.
Every server must be assigned as an indivisible unit to a single rack, though you may group servers onto racks in any combination. A group of servers fits together on one rack whenever their combined primary demand is at most A and their combined secondary demand is at most B. Resource capacities do not carry over from one coordinate to the other.
Implement min_racks(machines: List[List[int]], A: int, B: int) -> int to compute the smallest number of racks needed to accommodate every server:
- Return
0whenmachinesis empty. - Return
-1if at least one server exceedsAin its first coordinate orBin its second coordinate, making valid placement impossible.
Examples
Example 1
Input: machines = [[5, 2], [1, 6], [3, 5], [3, 3]], A = 6, B = 8
Output: 2
Explanation: Pairing [5, 2] with [1, 6] consumes (6, 8) on the first rack, and pairing [3, 5] with [3, 3] consumes (6, 8) on the second rack. Since total resource demand across all four servers is (12, 16), fewer than 2 racks is impossible.
Example 2
Input: machines = [[3, 3], [3, 3], [2, 4]], A = 7, B = 6
Output: 2
Explanation: Placing both [3, 3] servers onto the same rack uses (6, 6) <= (7, 6), while [2, 4] goes onto a second rack. Combining [2, 4] with [3, 3] would require 7 units of the second resource, exceeding B = 6.
Example 3
Input: machines = [[2, 4], [8, 1]], A = 7, B = 5
Output: -1
Explanation: The second server requests 8 units of the primary resource, which is strictly larger than a rack's primary limit A = 7, so no rack can hold it even by itself.
Constraints
0 <= len(machines) <= 20len(machines[i]) == 2for everyi0 <= machines[i][0], machines[i][1] <= 10^41 <= A, B <= 10^4
Step-by-step walkthrough
Understand the problem and edge-case rules
Each server
idemands(x_i, y_i)of two separate resources (such as CPU cores and RAM), and each uniform rack provides(A, B). A group of servers fits together on a single rack when theirxvalues add up to at mostAand theiryvalues add up to at mostB:Example 1: machines = [[5,2], [1,6], [3,5], [3,3]], rack capacity = (6, 8) Rack 1: (5, 2) + (1, 6) = (6, 8) <= (6, 8) fits! Rack 2: (3, 5) + (3, 3) = (6, 8) <= (6, 8) fits! Minimum racks = 2Check the two upfront boundary cases before running any search:
- If any server has
x_i > Aory_i > B(like[8, 1]under(7, 5)in Example 3), even a brand-new rack cannot hold it because coordinates do not trade off across dimensions — return-1right away. - If
machinesis empty,0racks are needed.
- If any server has
Why the naive subset bitmask DP takes `O(3^N)` time
2D bin packing is NP-hard, meaning no polynomial-time exact algorithm is known. For
Naround20, we represent each subset of placed machines as anN-bit integer called a bitmask, where biti(1 << i) is1if machineihas been placed and0otherwise:N = 4 machines: mask = 0b0000 (0) -> no machines placed {} mask = 0b0101 (5) -> machines 0 and 2 placed {0, 2} mask = 0b1111 (15) -> all 4 machines placed {0, 1, 2, 3}The textbook bitmask DP transitions by choosing an entire rack's group at once: for every
mask, try every submasksubofmaskwhose machines fit in a single rack (dp[mask] = min(1 + dp[mask ^ sub])). Across all2^Nmasks, enumerating all submasks visits3^Npairs — about3.5 * 10^9steps whenN = 20. Can we avoid enumerating submasks by placing one machine at a time instead?Key idea: fill one open rack at a time across all machine orders
Imagine keeping just one rack open on the loading dock and feeding machines one by one in some permutation:
- If the next machine
(req_x, req_y)fits in the open rack (used_x + req_x <= Aandused_y + req_y <= B), put it into the open rack. - Otherwise, seal the open rack and start a new open rack containing
(req_x, req_y).
Could this one-open-rack rule miss the optimal packing? Never! Take any optimal packing of
OPTracks and list its machines rack by rack (Rack 1's machines, thenRack 2's machines, and so on). All machines ofRack 1fit together, so the first rack never overflows. Each subsequent groupRack jcan trigger at most one new rack opening, because the moment one machine ofRack jstarts a fresh rack, all remaining machines ofRack jare guaranteed to fit alongside it (sum <= (A, B)). Thus at least one permutation achievesOPTracks — and our bitmask DP searches allN!permutations simultaneously by grouping states that have placed the exact samemask!- If the next machine
Why 2D needs a Pareto front of open-rack loads
Many permutations place the same subset
maskof machines. Which states(rack_count, (used_x, used_y))formaskdo we need to keep, and which can we safely discard?- Smaller
rack_countalways wins. Suppose the remaining unplaced machines needpracks on their own. Any state atkracks can finish in at mostk + pracks (pack the remaining machines rack by rack), whereas any state already atk + 1racks has sealedkracks before touching the remaining machines, so it needs at leastk + pracks in total. Therefore, for eachmaskwe keep only the minimumrack_countfound. - In 1D, the single lightest load wins; in 2D, we keep the Pareto front. In 1D bin packing, load
2is strictly better than load5. In 2D, compare open-rack loads(2, 8)and(5, 3)inside a(10, 10)rack:
Load A = (2, 8) -> 8 units of X free, only 2 units of Y free (good for X-heavy machines) Load B = (5, 3) -> 5 units of X free, 7 units of Y free (good for Y-heavy machines) Load C = (6, 8) -> worse or equal to Load A in BOTH resources (2 <= 6 and 8 <= 8) -> DROP!Load C is dominated by Load A (
2 <= 6and8 <= 8): any future machine that fits on(6, 8)also fits on(2, 8). Neither Load A nor Load B dominates the other, so keeping just one of them (for instance, sorting by(x, y)orx + y) actually produces wrong answers! Instead, we keep the Pareto front — all loads not dominated by any other load.- Smaller
Build `pareto_front` with a single sort and sweep
How do we filter a list of
(used_x, used_y)pairs down to its Pareto front cleanly? Sort the tuples in ascending order (used_xascending, breaking ties byused_yascending), and sweep left to right while trackingmin_y_so_far:Candidate loads: [(4, 4), (2, 5), (2, 3), (4, 2)] Sorted ascending: [(2, 3), (2, 5), (4, 2), (4, 4)] 1. (2, 3): min_y_so_far is None -> KEEP (2, 3), min_y_so_far = 3 2. (2, 5): 5 < 3 is False -> DROP (dominated by (2, 3)) 3. (4, 2): 2 < 3 is True -> KEEP (4, 2), min_y_so_far = 2 4. (4, 4): 4 < 2 is False -> DROP (dominated by (4, 2)) Pareto front: [(2, 3), (4, 2)]Because every earlier kept load already has
prev_x <= used_x, a candidate avoids being dominated (and avoids duplicates or worse ties on the sameused_x) if and only ifused_y < min_y_so_far! Moreover, since kept points have strictly increasingused_xin[0, A]and strictly decreasingused_yin[0, B], a Pareto front holds at mostmin(A, B) + 1loads.from typing import List, Optional, Tuple def pareto_front(loads: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """Keep only non-dominated (used_x, used_y) loads where no other load is <= in both dimensions.""" front: List[Tuple[int, int]] = [] min_y_so_far: Optional[int] = None for used_x, used_y in sorted(loads): if min_y_so_far is None or used_y < min_y_so_far: front.append((used_x, used_y)) min_y_so_far = used_y return frontSet up the DP tables and transitions
First, return
-1if any machine hasreq_x > Aorreq_y > B, and0ifn == 0. Otherwise create two arrays of length1 << n:min_rack_count[mask]: fewest racks used so far (counting the open rack), initialized ton + 1.open_rack_loads[mask]: candidate(used_x, used_y)pairs on the open rack achievingmin_rack_count[mask].
Start at
mask = 0with1empty open rack (min_rack_count[0] = 1,open_rack_loads[0] = [(0, 0)]). Becausemask | (1 << i)is always a larger integer thanmask, loopingfor mask in range(1 << n):guarantees every subset is complete before we prune its loads topareto_frontand push transitions tonext_mask = mask | (1 << i). Clearingopen_rack_loads[mask] = []right after pruning frees memory for already-processed masks.Trace Example 2 (`[[3, 3], [3, 3], [2, 4]]`, `A = 7`, `B = 6`)
mask (binary) | placed servers | min_rack_count | pareto_front | why --------------+-------------------+----------------+----------------------+------------------------------------------ 0b000 | {} | 1 | [(0, 0)] | 1 empty open rack 0b001 | {m0=(3,3)} | 1 | [(3, 3)] | fits on rack 1 0b010 | {m1=(3,3)} | 1 | [(3, 3)] | fits on rack 1 0b100 | {m2=(2,4)} | 1 | [(2, 4)] | fits on rack 1 0b011 | {m0, m1} | 1 | [(6, 6)] | (3+3, 3+3) = (6, 6) <= (7, 6) -> 1 rack! 0b101 | {m0, m2} | 2 | [(2, 4), (3, 3)] | (3+2, 3+4) = (5, 7) > (7, 6) -> 2 racks 0b110 | {m1, m2} | 2 | [(2, 4), (3, 3)] | (3+2, 3+4) = (5, 7) > (7, 6) -> 2 racks 0b111 | {m0, m1, m2} | 2 | [(2, 4), (3, 3)] | 0b011 opens rack 2 for (2, 4) -> return 2And on Example 1 (
[[5, 2], [1, 6], [3, 5], [3, 3]]with(6, 8)), incompatible 2-server masks like{0, 2}((5, 2)and(3, 5), summing to8 > 6inx) spill onto2racks, whereas{0, 1}((5, 2) + (1, 6) = (6, 8)) stays on1rack, opens Rack 2 for(3, 5), and packs(3, 3)into Rack 2 ((3+3, 5+3) = (6, 8)), finishing withmin_rack_count[0b1111] = 2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def pareto_front(loads: List[Tuple[int, int]]) -> List[Tuple[int, int]]: """Keep only non-dominated (used_x, used_y) loads where no other load is <= in both dimensions.""" front: List[Tuple[int, int]] = [] min_y_so_far: Optional[int] = None # Sorting tuples ascending orders by used_x first, breaking ties by used_y ascending. # Every earlier kept point already has prev_x <= used_x, so the current point avoids # being dominated (and avoids duplicates) if and only if used_y < min_y_so_far. for used_x, used_y in sorted(loads): if min_y_so_far is None or used_y < min_y_so_far: front.append((used_x, used_y)) min_y_so_far = used_y return front def min_racks(machines: List[List[int]], A: int, B: int) -> int: n = len(machines) # Phase 1: Check feasibility and empty input. # Any single machine exceeding A or B in either resource can never fit in any rack. for req_x, req_y in machines: if req_x > A or req_y > B: return -1 if n == 0: return 0 # Phase 2: Initialize bitmask DP over all 2^n subsets of placed machines. # min_rack_count[mask]: fewest racks used so far (counting the currently open rack). # open_rack_loads[mask]: candidate (used_x, used_y) loads on the open rack achieving min_rack_count[mask]. num_masks = 1 << n min_rack_count = [n + 1] * num_masks open_rack_loads: List[List[Tuple[int, int]]] = [[] for _ in range(num_masks)] # Start with 0 placed machines and 1 empty open rack at load (0, 0). min_rack_count[0] = 1 open_rack_loads[0] = [(0, 0)] # Phase 3: Expand masks in increasing order so every subset is finalized before its supersets. for mask in range(num_masks): current_racks = min_rack_count[mask] # Prune dominated open-rack loads, then clear the raw list to reclaim memory. front = pareto_front(open_rack_loads[mask]) open_rack_loads[mask] = [] for used_x, used_y in front: for i in range(n): machine_bit = 1 << i if mask & machine_bit: continue req_x, req_y = machines[i] # Place machine i in the open rack if both resources fit; otherwise open a fresh rack. # Opening a fresh rack when machine i already fits would use current_racks + 1 racks, # which can never beat keeping current_racks. if used_x + req_x <= A and used_y + req_y <= B: next_racks = current_racks next_load = (used_x + req_x, used_y + req_y) else: next_racks = current_racks + 1 next_load = (req_x, req_y) next_mask = mask | machine_bit if next_racks < min_rack_count[next_mask]: min_rack_count[next_mask] = next_racks open_rack_loads[next_mask] = [next_load] elif next_racks == min_rack_count[next_mask]: open_rack_loads[next_mask].append(next_load) return min_rack_count[num_masks - 1]✅ Submit now — all tests should pass.
Intuition & how it works
Think of loading servers onto data-center racks where each server demands both CPU cores (x) and RAM (y), and you keep just one rack open on the loading dock at a time: if the next server fits in the open rack across both resources, slide it in; otherwise seal that rack and wheel out a new one. Packing items whose resource coordinates add independently is called 2D vector bin packing, and we solve it exactly with bitmask dynamic programming (DP) — encoding each subset of placed machines as an N-bit integer mask so all permutations that placed the same subset merge their work. For each mask, we keep the minimum number of racks used so far alongside the Pareto front of open-rack loads — the set of (used_x, used_y) pairs where no other pair uses less-or-equal CPU and less-or-equal RAM simultaneously.
Why do simpler approaches fail or run too slowly? Trying all partitions of N machines grows like the Bell numbers (> 5 * 10^13 splits at N = 20), and the textbook bitmask DP that tests every submask of every mask still takes O(3^N) steps (~3.5 * 10^9 operations at N = 20). Greedy heuristics like sorting machines from largest to smallest and placing each in the first rack where it fits are fast, but frequently miss complementary pairs (such as pairing CPU-heavy [5, 2] with RAM-heavy [1, 6] inside (6, 8)) and use extra racks. Finally, copying the classic 1D bin-packing DP that stores only one "lightest" open-rack load per mask fails in 2D because (2, 8) has more free CPU while (5, 3) has more free RAM — discarding either one can forfeit the optimal packing!
Let's trace Example 2 with 3 machines [[3, 3], [3, 3], [2, 4]] and rack capacity (7, 6):
Start: mask = 0b000 -> 1 open rack, front = [(0, 0)]
1-machine masks:
0b001 {m0=(3,3)} -> 1 rack, front = [(3, 3)]
0b010 {m1=(3,3)} -> 1 rack, front = [(3, 3)]
0b100 {m2=(2,4)} -> 1 rack, front = [(2, 4)]
2-machine masks:
0b011 {m0, m1}: (3,3) + (3,3) = (6,6) <= (7,6) -> fits in 1 rack! front = [(6, 6)]
0b101 {m0, m2}: (3,3) + (2,4) = (5,7) > (7,6) -> opens rack 2; candidates [(2,4), (3,3)]
pareto_front([(2,4), (3,3)]) keeps BOTH [(2, 4), (3, 3)] (neither dominates!)
0b110 {m1, m2}: (3,3) + (2,4) = (5,7) > (7,6) -> opens rack 2; front = [(2, 4), (3, 3)]
3-machine mask:
0b111 {m0, m1, m2}: from 0b011 (1 rack, (6,6)) + m2=(2,4) -> opens rack 2 with (2, 4).
Result: min_rack_count[0b111] = 2 racks ({(3,3), (3,3)} and {(2,4)}).
Complexity
Let N be the number of machines and F be the maximum size of pareto_front across all 2^N masks.
- Time:
O(2^N * N * F * log(N * F)). There are2^Nmasks; each mask receives at mostN * Fcandidate loads from itsNsingle-bit predecessors, sorts them inO(N * F * log(N * F))time to extract at mostFPareto-optimal loads, and tries adding at mostNunplaced machines to each of thoseFloads. Because Pareto-optimal points have strictly increasing integerxin[0, A]and strictly decreasing integeryin[0, B],F <= min(A, B) + 1(and alsoF <= 2^|mask|, capping total transitions atN * 3^Neven for huge capacities). WhenFis small,2^N * NatN = 20is~2.1 * 10^7steps instead of3^20 ≈ 3.5 * 10^9. - Space:
O(2^N * N * F)worst case (with eager cleanup).min_rack_countstores2^Nintegers, andopen_rack_loadsholds candidate tuples for masks not yet processed (at mostNincoming transitions per Pareto point); settingopen_rack_loads[mask] = []right after computingfrontimmediately frees memory for completed masks.
Edge cases
- Empty
machineslist ([]): Returns0immediately (don't return the1open rack initialized atmask = 0!). - Oversized machine (
req_x > Aorreq_y > B): Returns-1before starting the DP, even if the other resource is tiny (e.g.,[6, 0]withA = 5, B = 5). - Exact capacity fit (
used_x + req_x == Aandused_y + req_y == B): Allowed (<=, not<), so[[2, 3], [3, 2]]fits in1rack of(5, 5). - Zero resource demand (
[0, 3]or[4, 0]): Consumes0in one coordinate while still counting toward the other ([[0, 3], [0, 3], [4, 0]]packs into1rack of(4, 6)). - Bottleneck in a single dimension (
[[1, 3], [1, 3], [1, 3]]with(10, 5)): Requires3racks because any two machines sum to6 > 5iny, despite using almost none ofA = 10. - Duplicate machines (
[[2, 2]] * 7): Many permutations produce identical(used_x, used_y)loads on the samemask;used_y < min_y_so_farinsidepareto_frontdeduplicates them automatically.
Common mistakes
- Keeping only one "smallest" load per
mask(the 1D bin-packing DP): Choosing a single load bymin(loads)(lexicographical(x, y)) ormin(x + y)drops incomparable trade-off states and fails on inputs like[[3, 5], [2, 8], [3, 8], [2, 10], [4, 5], [3, 4]]with(10, 20)(returning3instead of2). - Using
<=instead of<inpareto_front: Writingused_y <= min_y_so_farkeeps dominated points with largerxand equaly(like keeping(4, 3)after(2, 3)) as well as exact duplicate tuples, blowing upfrontsize unnecessarily. - Relying on greedy First-Fit Decreasing for exactness: Sorting by
x,y,x/A + y/B, ormax(x/A, y/B)and placing greedily uses3racks on[[2, 4], [4, 2], [1, 5], [3, 6], [6, 1]]with(9, 10), whereas the optimal packing uses2racks ({(3, 6), (4, 2)}and{(2, 4), (1, 5), (6, 1)}). - Checking combined capacity
x + y <= A + B: Resources are not interchangeable across dimensions; each coordinate must satisfy its own cap independently. - Skipping the upfront
-1check: Without checkingreq_x > A or req_y > Bfirst, theelsebranch would happily open a fresh rack(req_x, req_y)for an impossible machine and return a bogus positive rack count.
Alternative approaches
- Submask-enumeration bitmask DP (
O(3^N)time,O(2^N)space): Precomputefits[mask]for every subset whosex-sum<= Aandy-sum<= B, fix the lowest set bitlow = mask & -maskto avoid permuting rack order, and iteratesub = mask; while sub: ... sub = (sub - 1) & mask. Simple to code and capacity-independent, handlingN <= 15comfortably in Python. - Branch-and-Bound backtracking: Sort machines in decreasing order of
max(x_i / A, y_i / B), try placing machineiinto each distinct existing rack load or one new rack, and prune any branch as soon aslen(racks) + ceil(remaining_x / A)orlen(racks) + ceil(remaining_y / B)meets or exceeds the best solution found so far. - Integer Linear Programming (ILP) / Column Generation: For larger exact industrial instances (
N = 50..200), formulate set covering over feasible rack patterns or binary assignment variablesz_{i, r} in {0, 1}in an MILP solver.
Follow-up questions
- What approach would you take when the fleet grows to thousands of machines where exponential search is no longer viable? Exact exponential algorithms are infeasible at that scale, so use a fast constructive heuristic — such as First-Fit Decreasing or Best-Fit Decreasing ordered by
max(x_i / A, y_i / B)(or dot-product alignment with remaining rack capacity) — followed by local-search swaps that try to empty the least-loaded rack. Always pair the heuristic with fast lower bounds likemax(ceil(sum(x) / A), ceil(sum(y) / B))so you can measure how close your packing is to optimal (and stop immediately if they match). - Can you achieve better than O(3^N) worst-case exact runtime even when the rack capacities A and B are arbitrarily large? Yes, via inclusion-exclusion with Sum-Over-Subsets (SOS) DP (a dynamic programming transform that sums values over all
2^|X|subsets of every maskXinO(N * 2^N)total additions). First markfits[S] = 1for every subsetSthat fits in one rack (including emptyS), computef[X]= number of fitting subsets insideXfor allXinO(N * 2^N), and then fork = 1..Ncheck whethersum_{X} (-1)^(N - |X|) * f[X]^k > 0(the number of wayskfitting subsets can cover allNmachines); the firstkwith a positive sum is the minimum rack count, takingO(N * 2^N)arithmetic operations total. - How would your DP state and pruning step adapt if each machine specified d >= 3 independent resource dimensions? The bitmask DP structure stays identical, replacing
(used_x, used_y)with ad-tuple and checking alldcapacitiesused[c] + req[c] <= cap[c]. Ford >= 3, a single left-to-right sweep no longer computes the Pareto front, so you filtermcandidated-tuples pairwise inO(m^2 * d)time (keeping tuples not<=in alldcoordinates), and the front sizeFcan grow withd - 1coordinates up to2^|mask|.
Follow-up questions
- What approach would you take when the fleet grows to thousands of machines where exponential search is no longer viable?
- Can you achieve better than O(3^N) worst-case exact runtime even when the rack capacities A and B are arbitrarily large?
- How would your DP state and pruning step adapt if each machine specified d >= 3 independent resource dimensions?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array