Bin-Pack Pods onto Nodes (First-Fit Decreasing)
Problem Statement
Estimate how many identical nodes are needed to schedule a set of pods by CPU request using first-fit-decreasing bin packing.
Background
Each node has node_cpu allocatable CPU. Pods are sorted by CPU request descending, then each is placed in the first node with enough remaining CPU; if none fits, a new node is opened. Return the number of nodes used. A pod larger than node_cpu is unschedulable — return -1.
Your Task
def pack_nodes(pod_cpus, node_cpu):
Return the node count, or -1 if any pod exceeds a node.
Input Format
- pod_cpus (list of numbers), node_cpu (number).
Output Format
- An int (node count) or -1.
Sample
print(pack_nodes([3, 3, 2, 2, 1], 4))
Output:
3
Example
print(pack_nodes([3, 3, 2, 2, 1], 4))
3
- Check for unschedulable pods: Verify that no single pod exceeds the node capacity. Since the maximum pod CPU is and the node capacity is (), all pods are schedulable, so we proceed with packing.
- Sort pods in descending order: To apply the First-Fit Decreasing strategy, sort the input list to get .
- Place the first two pods: The first pod () does not fit in any existing node, so Node 1 is opened with remaining capacity . The second pod () does not fit in Node 1 (), so Node 2 is opened with remaining capacity .
- Place the next two pods: The third pod () does not fit in Node 1 or Node 2 (both have only remaining), so Node 3 is opened with remaining capacity . The fourth pod () fits into the first available node with sufficient space, which is Node 3 (), updating Node 3's remaining capacity to .
- Place the final pod and count nodes: The last pod () fits into Node 1 (remaining ), updating Node 1's remaining capacity to . The total number of nodes used is .
The final output is 3
Constraints
- Sort pods descending, first-fit into node remaining capacity.
- Open a new node when none fits.
- Any pod > node_cpu -> return -1.