TExcelTAD
Home › Approximation Algorithms › Bin Packing: First Fit and First-Fit Decreasing

Bin Packing: First Fit and First-Fit Decreasing

Bin packing: items with sizes s1,…,sn∈(0,1]s_1, \ldots, s_n \in (0, 1] must be packed into as few bins of capacity 1 as possible. It models cutting stock, loading trucks, allocating memory pages and placing virtual machines on servers. It is NP-hard and, as shown below, cannot be approximated within a factor below 32\frac{3}{2} unless P = NP. Yet simple greedy rules come close to optimal when the optimum is large, which makes bin packing the standard example of the gap between absolute and asymptotic ratios. This lesson analyses Next Fit, First Fit and First-Fit Decreasing; the next one shows that the asymptotic ratio can be pushed to 1+ε1 + \varepsilon.

The lower bound and the hardness

The total size S=∑isiS = \sum_i s_i is a lower bound: OPT≥⌈S⌉\text{OPT} \ge \lceil S \rceil. Almost every analysis compares with it.

Theorem. For every ε>0\varepsilon > 0 there is no (32−ε)(\frac{3}{2} - \varepsilon)-approximation for bin packing unless P = NP.

Proof. PARTITION asks whether positive integers a1,…,ana_1, \ldots, a_n can be split into two halves of equal sum A=12∑iaiA = \frac{1}{2}\sum_i a_i; it is NP-complete. Map it to the items si=aiAs_i = \frac{a_i}{A}. They fit into 2 bins exactly when the answer is yes; otherwise 3 bins are needed (and always enough, by Next Fit below). An algorithm with ratio below 32\frac{3}{2} must return 2 bins on yes-instances, since 3 would be a ratio of 32\frac{3}{2}, so it decides PARTITION. □\square

The argument only works because OPT is tiny. An asymptotic guarantee ALG≤ρ OPT+c\text{ALG} \le \rho\,\text{OPT} + c escapes it, and that is where the good algorithms live.

The gap is not hypothetical. The program searches small PARTITION instances for one where the items fit into 2 bins but First-Fit Decreasing, a good heuristic, uses 3, which is exactly a ratio of 32\frac{3}{2}. Two-bin feasibility is checked with the subset-sum dynamic program (the practice problem Subset Sum).

python · try it yourself
import random

def ffd(items, cap):
    rooms = []
    for s in sorted(items, reverse=True):
        for i, r in enumerate(rooms):
            if s <= r:
                rooms[i] -= s
                break
        else:
            rooms.append(cap - s)
    return len(rooms)

def splits_evenly(a):
    total = sum(a)
    if total % 2:
        return False
    reach = {0}
    for x in a:
        reach |= {r + x for r in reach}
    return total // 2 in reach

rng = random.Random(3)
found = 0
for trial in range(2000):
    a = [rng.randint(1, 12) for _ in range(rng.randint(5, 8))]
    if splits_evenly(a) and ffd(a, sum(a) // 2) == 3:
        print(f"items {sorted(a, reverse=True)}, bins of size {sum(a) // 2}: OPT 2, FFD 3")
        found += 1
        if found == 3:
            break
items [11, 11, 8, 7, 5, 4], bins of size 23: OPT 2, FFD 3
items [12, 10, 6, 6, 5, 5, 3, 1], bins of size 24: OPT 2, FFD 3
items [11, 9, 8, 7, 7, 7, 3], bins of size 26: OPT 2, FFD 3

On each of these instances the optimum is a perfect split, but FFD commits to the largest items first and cannot find it. No polynomial algorithm can avoid this on all instances unless P = NP.

Next Fit and First Fit

text
NEXT-FIT:  keep one open bin; if the item does not fit, close it and open a new one
FIRST-FIT: put the item into the first (lowest-index) bin where it fits; open a new bin if none

Theorem. Next Fit uses at most 2⌈S⌉−1≤2 OPT−12\lceil S \rceil - 1 \le 2\,\text{OPT} - 1 bins. First Fit uses at most 2 OPT2\,\text{OPT} bins.

Proof. In Next Fit, any two consecutive bins together hold more than 1, since the first item of the second bin did not fit in the first. With kk bins, pairing bins 1+21+2, 3+43+4, and so on gives S>⌊k2⌋S > \lfloor \frac{k}{2} \rfloor, so k≤2⌈S⌉−1k \le 2\lceil S \rceil - 1. In First Fit, at most one bin is at most half full: if two were, the items of the later one would have fit into the earlier one. So all bins but one hold more than 12\frac{1}{2}, giving k−12<S\frac{k - 1}{2} < S, so k≤2⌈S⌉k \le 2\lceil S \rceil. □\square

The truth for First Fit is better: Ullman (1971) and Garey, Graham, Johnson and Yao (1976) proved FF≤1710 OPT+2\text{FF} \le \frac{17}{10}\,\text{OPT} + 2, and Dósa and Sgall (2013) proved the clean absolute bound FF≤⌊1710 OPT⌋\text{FF} \le \lfloor \frac{17}{10}\,\text{OPT} \rfloor, which is tight. Both are online algorithms: they place each item without seeing the next.

First-Fit Decreasing

Sorting the items from largest to smallest before running First Fit (FFD) helps, for the same reason LPT helps scheduling (Longest Processing Time First): large items are hard to place, small ones fill gaps.

Theorem. FFD uses at most 32 OPT+1\frac{3}{2}\,\text{OPT} + 1 bins.

Proof. Look at the item xx that opened the last bin. Case 1: sx>13s_x > \frac{1}{3}. Delete all items after xx in the sorted order: FFD packs the remaining items exactly as before, so it still uses the same number of bins, and OPT does not grow. All remaining items exceed 13\frac{1}{3}, so every bin holds at most two of them, and for such instances FFD is optimal (an exchange argument like the one for LPT: FFD places the large items one per bin and then fits each smaller item, largest first, into the fullest bin where it fits, which some optimal packing can be transformed into). So FFD == OPT. Case 2: sx≤13s_x \le \frac{1}{3}. Then every bin before the last has free space less than 13\frac{1}{3}, otherwise xx would have gone there, so with kk bins S>23(k−1)S > \frac{2}{3}(k - 1) and k<32S+1≤32OPT+1k < \frac{3}{2}S + 1 \le \frac{3}{2}\text{OPT} + 1. □\square

The exact constant took decades. Johnson (1973) proved FFD≤119 OPT+4\text{FFD} \le \frac{11}{9}\,\text{OPT} + 4 in a long case analysis, Baker (1985) and Yue (1991) lowered the additive constant, and Dósa (2007) proved the tight bound

FFD≤119 OPT+69.\text{FFD} \le \frac{11}{9}\,\text{OPT} + \frac{6}{9} .

The family below attains 119\frac{11}{9} with capacity 100 and items 51,27,26,2351, 27, 26, 23 (half plus a little, and quarters perturbed). With 6m6m items of each of the first three sizes and 12m12m of size 23, the optimum packs 6m6m bins as 51+26+2351 + 26 + 23 and 3m3m bins as 27+27+23+2327 + 27 + 23 + 23, all exactly full: 9m9m bins. FFD puts each 51 with a 27 (78, no room for 23), then the 26s three to a bin (78 again), then the 23s four to a bin: 6m+2m+3m=11m6m + 2m + 3m = 11m bins.

python · try it yourself
import random

def next_fit(items):
    bins, room = 0, 0
    for s in items:
        if s > room:
            bins, room = bins + 1, 100
        room -= s
    return bins

def first_fit(items):
    rooms = []
    for s in items:
        for i, r in enumerate(rooms):
            if s <= r:
                rooms[i] -= s
                break
        else:
            rooms.append(100 - s)
    return len(rooms)

def ffd(items):
    return first_fit(sorted(items, reverse=True))

def optimum(items):
    items = sorted(items, reverse=True)
    def fits(k):
        rooms = [100] * k
        def place(i):
            if i == len(items):
                return True
            tried = set()
            for b in range(k):
                if rooms[b] >= items[i] and rooms[b] not in tried:   # skip bins with equal room: symmetry
                    tried.add(rooms[b])
                    rooms[b] -= items[i]
                    if place(i + 1):
                        return True
                    rooms[b] += items[i]
            return False
        return place(0)
    k = -(-sum(items) // 100)
    while not fits(k):
        k += 1
    return k

rng = random.Random(14)
print("  n  ceil(S)  NF  FF  FFD  OPT")
for n in [10, 12, 14, 16]:
    items = [rng.randint(10, 70) for _ in range(n)]
    print(f"{n:3} {-(-sum(items) // 100):8} {next_fit(items):3} {first_fit(items):3} {ffd(items):4} {optimum(items):4}")
for m in [1, 2, 3]:
    items = [51] * (6 * m) + [27] * (6 * m) + [26] * (6 * m) + [23] * (12 * m)
    print(f"FFD family m = {m}: FFD {ffd(items)}, OPT {9 * m} (all bins exactly full), ratio {ffd(items) / (9 * m):.4f}")
  n  ceil(S)  NF  FF  FFD  OPT
 10        5   6   6    5    5
 12        5   7   5    5    5
 14        7   9   7    7    7
 16        6   6   6    6    6
FFD family m = 1: FFD 11, OPT 9 (all bins exactly full), ratio 1.2222
FFD family m = 2: FFD 22, OPT 18 (all bins exactly full), ratio 1.2222
FFD family m = 3: FFD 33, OPT 27 (all bins exactly full), ratio 1.2222

In C++

First-Fit Decreasing with a linear scan over the bins. A balanced tree of bins keyed by remaining room (or a segment tree over bin indices) brings First Fit down to O(nlog⁡n)O(n \log n).

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <functional>
#include <vector>

int main() {
    std::vector<int> items = {44, 24, 24, 22, 21, 17, 8, 8, 6, 6, 52, 33, 61, 15, 39};
    std::sort(items.begin(), items.end(), std::greater<int>());
    std::vector<int> room;
    std::vector<std::vector<int>> content;
    for (int s : items) {
        size_t b = 0;
        while (b < room.size() && room[b] < s) b++;
        if (b == room.size()) { room.push_back(100); content.emplace_back(); }
        room[b] -= s;
        content[b].push_back(s);
    }
    int total = 0;
    for (int s : items) total += s;
    for (size_t b = 0; b < content.size(); b++) {
        std::printf("bin %zu:", b);
        for (int s : content[b]) std::printf(" %d", s);
        std::printf("  (free %d)\n", room[b]);
    }
    std::printf("%zu bins, lower bound ceil(S) = %d\n", content.size(), (total + 99) / 100);
}
bin 0: 61 39  (free 0)
bin 1: 52 44  (free 4)
bin 2: 33 24 24 17  (free 2)
bin 3: 22 21 15 8 8 6 6  (free 14)
4 bins, lower bound ceil(S) = 4

In practice

  • Online settings (memory allocators, cloud placement) must use online rules such as First Fit or Best Fit (the fullest bin where the item fits); no online algorithm has asymptotic ratio below about 1.54 (lower bounds by Yao, 1980, and later work).
  • Offline, FFD and Best-Fit Decreasing are the default heuristics and are usually within a few percent of the lower bound ⌈S⌉\lceil S \rceil. Exact solvers combine such bounds with branch and bound or the configuration LP, the subject of the next lesson.
  • Vector bin packing (several resources per item, as for CPU and memory of virtual machines) is harder: no asymptotic PTAS exists even in two dimensions unless P = NP (Woeginger, 1997).

Test yourself

Why can no algorithm have an absolute ratio below 32\frac{3}{2} for bin packing unless P = NP?

  1. Because First Fit is optimal
  2. Instances from PARTITION need 2 bins (yes) or 3 bins (no), and a ratio below 32\frac{3}{2} forces the answer 2 on yes-instances
  3. Because the LP relaxation has gap 32\frac{3}{2}
  4. Because items can be larger than 12\frac{1}{2}

Why does First Fit use at most 2⌈S⌉2\lceil S \rceil bins?

  1. Because items are sorted
  2. At most one bin is at most half full: the items of a later half-empty bin would have fit into an earlier one
  3. Because each bin holds at least two items
  4. Because Next Fit uses fewer bins

What is the tight asymptotic guarantee of First-Fit Decreasing proved by Dósa (2007)?

  1. FFD≤32OPT\text{FFD} \le \frac{3}{2}\text{OPT}
  2. FFD≤119OPT+69\text{FFD} \le \frac{11}{9}\text{OPT} + \frac{6}{9}
  3. FFD≤1710OPT\text{FFD} \le \frac{17}{10}\text{OPT}
  4. FFD≤OPT+1\text{FFD} \le \text{OPT} + 1