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 0 when machines is empty.
  • Return -1 if at least one server exceeds A in its first coordinate or B in 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) <= 20
  • len(machines[i]) == 2 for every i
  • 0 <= machines[i][0], machines[i][1] <= 10^4
  • 1 <= A, B <= 10^4

Step-by-step walkthrough

  1. Understand the problem and edge-case rules

    Each server i demands (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 their x values add up to at most A and their y values add up to at most B:

    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 = 2
    

    Check the two upfront boundary cases before running any search:

    • If any server has x_i > A or y_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 -1 right away.
    • If machines is empty, 0 racks are needed.
  2. 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 N around 20, we represent each subset of placed machines as an N-bit integer called a bitmask, where bit i (1 << i) is 1 if machine i has been placed and 0 otherwise:

    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 submask sub of mask whose machines fit in a single rack (dp[mask] = min(1 + dp[mask ^ sub])). Across all 2^N masks, enumerating all submasks visits 3^N pairs — about 3.5 * 10^9 steps when N = 20. Can we avoid enumerating submasks by placing one machine at a time instead?

  3. 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 <= A and used_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 OPT racks and list its machines rack by rack (Rack 1's machines, then Rack 2's machines, and so on). All machines of Rack 1 fit together, so the first rack never overflows. Each subsequent group Rack j can trigger at most one new rack opening, because the moment one machine of Rack j starts a fresh rack, all remaining machines of Rack j are guaranteed to fit alongside it (sum <= (A, B)). Thus at least one permutation achieves OPT racks — and our bitmask DP searches all N! permutations simultaneously by grouping states that have placed the exact same mask!

  4. Why 2D needs a Pareto front of open-rack loads

    Many permutations place the same subset mask of machines. Which states (rack_count, (used_x, used_y)) for mask do we need to keep, and which can we safely discard?

    1. Smaller rack_count always wins. Suppose the remaining unplaced machines need p racks on their own. Any state at k racks can finish in at most k + p racks (pack the remaining machines rack by rack), whereas any state already at k + 1 racks has sealed k racks before touching the remaining machines, so it needs at least k + p racks in total. Therefore, for each mask we keep only the minimum rack_count found.
    2. In 1D, the single lightest load wins; in 2D, we keep the Pareto front. In 1D bin packing, load 2 is strictly better than load 5. 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 <= 6 and 8 <= 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) or x + y) actually produces wrong answers! Instead, we keep the Pareto front — all loads not dominated by any other load.

  5. 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_x ascending, breaking ties by used_y ascending), and sweep left to right while tracking min_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 same used_x) if and only if used_y < min_y_so_far! Moreover, since kept points have strictly increasing used_x in [0, A] and strictly decreasing used_y in [0, B], a Pareto front holds at most min(A, B) + 1 loads.

    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 front
    
  6. Set up the DP tables and transitions

    First, return -1 if any machine has req_x > A or req_y > B, and 0 if n == 0. Otherwise create two arrays of length 1 << n:

    • min_rack_count[mask]: fewest racks used so far (counting the open rack), initialized to n + 1.
    • open_rack_loads[mask]: candidate (used_x, used_y) pairs on the open rack achieving min_rack_count[mask].

    Start at mask = 0 with 1 empty open rack (min_rack_count[0] = 1, open_rack_loads[0] = [(0, 0)]). Because mask | (1 << i) is always a larger integer than mask, looping for mask in range(1 << n): guarantees every subset is complete before we prune its loads to pareto_front and push transitions to next_mask = mask | (1 << i). Clearing open_rack_loads[mask] = [] right after pruning frees memory for already-processed masks.

  7. 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 2
    

    And 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 to 8 > 6 in x) spill onto 2 racks, whereas {0, 1} ((5, 2) + (1, 6) = (6, 8)) stays on 1 rack, opens Rack 2 for (3, 5), and packs (3, 3) into Rack 2 ((3+3, 5+3) = (6, 8)), finishing with min_rack_count[0b1111] = 2.

  8. 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 are 2^N masks; each mask receives at most N * F candidate loads from its N single-bit predecessors, sorts them in O(N * F * log(N * F)) time to extract at most F Pareto-optimal loads, and tries adding at most N unplaced machines to each of those F loads. Because Pareto-optimal points have strictly increasing integer x in [0, A] and strictly decreasing integer y in [0, B], F <= min(A, B) + 1 (and also F <= 2^|mask|, capping total transitions at N * 3^N even for huge capacities). When F is small, 2^N * N at N = 20 is ~2.1 * 10^7 steps instead of 3^20 ≈ 3.5 * 10^9.
  • Space: O(2^N * N * F) worst case (with eager cleanup). min_rack_count stores 2^N integers, and open_rack_loads holds candidate tuples for masks not yet processed (at most N incoming transitions per Pareto point); setting open_rack_loads[mask] = [] right after computing front immediately frees memory for completed masks.

Edge cases

  • Empty machines list ([]): Returns 0 immediately (don't return the 1 open rack initialized at mask = 0!).
  • Oversized machine (req_x > A or req_y > B): Returns -1 before starting the DP, even if the other resource is tiny (e.g., [6, 0] with A = 5, B = 5).
  • Exact capacity fit (used_x + req_x == A and used_y + req_y == B): Allowed (<=, not <), so [[2, 3], [3, 2]] fits in 1 rack of (5, 5).
  • Zero resource demand ([0, 3] or [4, 0]): Consumes 0 in one coordinate while still counting toward the other ([[0, 3], [0, 3], [4, 0]] packs into 1 rack of (4, 6)).
  • Bottleneck in a single dimension ([[1, 3], [1, 3], [1, 3]] with (10, 5)): Requires 3 racks because any two machines sum to 6 > 5 in y, despite using almost none of A = 10.
  • Duplicate machines ([[2, 2]] * 7): Many permutations produce identical (used_x, used_y) loads on the same mask; used_y < min_y_so_far inside pareto_front deduplicates them automatically.

Common mistakes

  • Keeping only one "smallest" load per mask (the 1D bin-packing DP): Choosing a single load by min(loads) (lexicographical (x, y)) or min(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) (returning 3 instead of 2).
  • Using <= instead of < in pareto_front: Writing used_y <= min_y_so_far keeps dominated points with larger x and equal y (like keeping (4, 3) after (2, 3)) as well as exact duplicate tuples, blowing up front size unnecessarily.
  • Relying on greedy First-Fit Decreasing for exactness: Sorting by x, y, x/A + y/B, or max(x/A, y/B) and placing greedily uses 3 racks on [[2, 4], [4, 2], [1, 5], [3, 6], [6, 1]] with (9, 10), whereas the optimal packing uses 2 racks ({(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 -1 check: Without checking req_x > A or req_y > B first, the else branch 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): Precompute fits[mask] for every subset whose x-sum <= A and y-sum <= B, fix the lowest set bit low = mask & -mask to avoid permuting rack order, and iterate sub = mask; while sub: ... sub = (sub - 1) & mask. Simple to code and capacity-independent, handling N <= 15 comfortably in Python.
  • Branch-and-Bound backtracking: Sort machines in decreasing order of max(x_i / A, y_i / B), try placing machine i into each distinct existing rack load or one new rack, and prune any branch as soon as len(racks) + ceil(remaining_x / A) or len(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 variables z_{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 like max(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 mask X in O(N * 2^N) total additions). First mark fits[S] = 1 for every subset S that fits in one rack (including empty S), compute f[X] = number of fitting subsets inside X for all X in O(N * 2^N), and then for k = 1..N check whether sum_{X} (-1)^(N - |X|) * f[X]^k > 0 (the number of ways k fitting subsets can cover all N machines); the first k with a positive sum is the minimum rack count, taking O(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 a d-tuple and checking all d capacities used[c] + req[c] <= cap[c]. For d >= 3, a single left-to-right sweep no longer computes the Pareto front, so you filter m candidate d-tuples pairwise in O(m^2 * d) time (keeping tuples not <= in all d coordinates), and the front size F can grow with d - 1 coordinates up to 2^|mask|.

Follow-up questions

Similar questions

More Accenture interview questions

All 1 Accenture questions →