PIXELBANKv9.1.0
Menu

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:

Input:
print(pack_nodes([3, 3, 2, 2, 1], 4))
Output:
3
Reasoning:
  • Check for unschedulable pods: Verify that no single pod exceeds the node capacity. Since the maximum pod CPU is 33 and the node capacity is 44 (3≤43 \le 4), 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 [3,3,2,2,1][3, 3, 2, 2, 1] to get [3,3,2,2,1][3, 3, 2, 2, 1].
  • Place the first two pods: The first pod (33) does not fit in any existing node, so Node 1 is opened with remaining capacity 4−3=14 - 3 = 1. The second pod (33) does not fit in Node 1 (1<31 < 3), so Node 2 is opened with remaining capacity 4−3=14 - 3 = 1.
  • Place the next two pods: The third pod (22) does not fit in Node 1 or Node 2 (both have only 11 remaining), so Node 3 is opened with remaining capacity 4−2=24 - 2 = 2. The fourth pod (22) fits into the first available node with sufficient space, which is Node 3 (2+2≤42 + 2 \le 4), updating Node 3's remaining capacity to 00.
  • Place the final pod and count nodes: The last pod (11) fits into Node 1 (remaining 11), updating Node 1's remaining capacity to 00. The total number of nodes used is 33.

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

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.