Algorithmcore
Bottom-left fill heuristic
Also called bottom-left heuristic.
Places each part in turn at the lowest, then leftmost, position where it fits, often found with no-fit polygons. It is a base for nesting heuristics.
- Time
- O(n^3) worst
- Space
- O(n) extra
- Where
- n = number of rectangles
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Brenda S. Baker, Edward G. Coffman Jr., Ronald L. Rivest, Bernard Chazelle, 1980
Bottom-left fill (BLF) is a greedy placement rule for packing parts into a strip or a sheet. It takes the parts one at a time in a given order, and puts each one at the feasible position that is lowest, and among the lowest ones, leftmost. A position is feasible when the part stays inside the strip and does not overlap a part placed earlier. Positions in holes between earlier parts count, and this is the "fill" in the name. For rectangles the rule is the bottom-left rule of Baker, Coffman and Rivest (1980), who proved that with the rectangles sorted by decreasing width the strip height is at most 3 times the optimum. For polygons the feasible positions come from no-fit polygons. BLF is a heuristic for the nesting problem and for strip packing. Most solvers for the nesting problem use it as the decoder of a search over part orders. This page covers the hole-filling rule. The older sliding rule of Jakobs (1996), which moves a part down and left until it is stuck, is a different rule, and the page names it where the two differ.
In plain words
You must cut a list of shapes from a long roll of sheet metal of fixed width, and use as little of the roll as you can.
Take the shapes in the order of the list. For each shape, look for the lowest place on the roll where it fits without touching the inside of a shape you have already placed. If there are several such places at the same height, take the one most to the left. Put the shape there and go to the next one.
The rule can put a small shape into a gap that is closed on all sides, below a shape that was placed earlier. A rule that only pushes the shape down and to the left cannot reach such a gap.
The rule never moves a shape again, so the order of the list decides how good the result is.
The problem
The strip is . The input is a list of rectangles with widths and heights , and the output is a lower left corner for each. Rectangles may not rotate. Two placed rectangles overlap when their interiors meet. Touching edges and corners are allowed. The goal of strip packing is the least height . BLF does not solve that goal. It gives each rectangle the position that is least in the lexicographic order of among the feasible positions, given the rectangles before it. The polygon case is in Variants.
The algorithm
Two facts make the search finite. The lowest feasible height is or the top edge of a placed rectangle: at any other height the rectangle can move down a little. For a fixed height, the rectangles that meet the open band block the positions in the open intervals , and a scan from the left in the order of finds the least free .
BLF(W, R) ▷ strip width W, rectangles R[1..n] = (w, h)- 1
P ← empty list ▷ placed (x', y', w', h') - 2
for each (w, h) in R, in order do - 3
Y ← {0} ∪ {y' + h' : (x', y', w', h') ∈ P}, in increasing order - 4
for each y ∈ Y do - 5
x ← 0 - 6
for each (x', y', w', h') ∈ P with y' < y + h and y' + h' > y, by increasing x' do - 7
if x' ≥ x + w then break ▷ the gap before this one is wide enough - 8
x ← max(x, x' + w') - 9
if x + w ≤ W then - 10
append (x, y, w, h) to P and go to the next rectangle - 11
return P
Line L3 lists the candidate heights. Line L6 keeps the rectangles of the band, the only ones that can block a position at height . Line L7 stops as soon as the rectangle at ends before the next blocker starts. Line L8 moves to the right edge of a blocker. At the largest candidate height the band is empty, so line L9 succeeds there and every rectangle is placed.
Exact arithmetic. Every test is a comparison of sums of input numbers. With integer or rational sizes the result is exact, and the positions are themselves sums of sizes. With floating point sizes, a sum such as can compare wrong with , so a rectangle that fits exactly into a gap can be rejected, or two rectangles can overlap by a rounding error. Use integers in a fixed unit, or exact rationals. The degenerate cases are part of the input: a rectangle as wide as the strip, a rectangle that fits a gap exactly, and edges that touch are all handled by the strict inequalities of line L6 and the non-strict ones of lines L7 and L9.
Example
Take and the rectangles , , , , as (width, height), in this order.
| rectangle | candidate heights | what happens | position |
|---|---|---|---|
| empty strip | |||
| : moves to 2, and | |||
| : gives , gives , and | |||
| and : blocks, so and . : empty band | |||
| : goes to 2, 8, 10, fails. : band holds and only, gives , then starts at |
is a lid on the two posts and , so the region is a closed hole. goes into it. The final height is 6. The total area is 57, so no packing is lower than . A sliding rule that starts above the lid and pushes it down and left cannot reach the hole. It stops on top of at , and the packing is then 9 high.
Correctness
Feasible positions form a closed set, so a lexicographically least one exists. If its height were neither 0 nor a top edge, moving the rectangle down by a small amount would keep it feasible, because only a rectangle whose top edge is in the gap could block the move. So is in the list of line L3. For a fixed height the scan of lines L5 to L8 keeps two facts: is at or right of the right edge of every blocker seen so far, and every smaller is blocked by one of them. When the scan stops, is the least that nothing blocks, and line L9 checks the right wall. Trying the heights in increasing order gives the least , and then the least . The full proof is in proofs/correctness.md.
Proof: Bottom-left fill puts each rectangle at its lexicographically least feasible positionfull
Setting. The strip is . A placed rectangle is . A position of a new rectangle, with and , is feasible when , , and the interior of meets the interior of no placed rectangle. Two closed boxes have meeting interiors exactly when their open -intervals meet and their open -intervals meet, so is blocked by if and only if
Claim. Let be a finite set of placed rectangles with pairwise disjoint interiors inside the strip. Lines L3 to L10 return the feasible position that is least in the order of , that is, least first and least among those. Hence BLF places every rectangle, the placed rectangles stay pairwise disjoint in their interiors, and each one is at its bottom-left position with respect to the ones before it.
Step 1 (a least position exists). Let be the set of feasible positions. Condition (1) is a conjunction of strict inequalities, so the set of positions blocked by is open, and is the closed set minus a finite union of open sets. So is closed. It is not empty: with the largest top (or if is empty), the position fails for every . The set is closed and bounded, so it has a point with least , call it . The section is closed, bounded and not empty, so it has a least element .
Step 2 (the least height is a candidate). Let . Suppose . Then . Take smaller than and smaller than for every top with . We claim , which contradicts the choice of . Let satisfy (1) at . Its conditions do not depend on , so they hold at too. Also . Since is feasible, (1) fails there, so . With , the top lies in . It is not , because , so it lies in , which the choice of excludes. So no blocks , and .
Step 3 (the row scan). Fix . Let be the rectangles with and , the band of line L6, sorted by , and let . By (1), a position with is blocked by exactly when . Let be the value of after the loop has handled without a break, with . We show by induction that
(a) for every , so is in none of , because each of them is open at its right end ;
(b) every lies in some with .
Both hold for . For the step, look at at line L7. If , the loop breaks. Otherwise , and line L8 sets . Then (a) holds for at once. For (b), take . If , use (b) for . Otherwise , and with this gives .
Let the loop end with the value , after a break at or after all rectangles. In the case of a break, for all , so for . With (a), is in no , and by (b) every smaller is in some . So is the least that no rectangle blocks at height . Rectangles outside the band do not block at height by (1). Hence row has a feasible position if and only if , which is the test of line L9, and then is the least feasible in that row.
Step 4 (the answer). Line L4 tries the heights of in increasing order and returns at the first one whose row has a feasible position, with the least in that row. By Step 2, , and no has a feasible position, so the first such height is , and the returned is . The largest element of has an empty band, so line L9 succeeds there with , and the loop of line L4 always returns.
Corollaries. The returned position is feasible, so the interiors stay disjoint, and by induction on the input order this holds for the whole output. With integer sizes, every element of and every value of in the scan is a sum of input numbers, so the bottom-left position is a pair of integers. That is why a brute force over all integer positions finds the same position. For Fraction input the same holds with all values in the additive group generated by the sizes.
Termination. Each loop runs over a finite list, and the outer loop of line L2 places one rectangle per pass.
Complexity
For the -th rectangle, line L3 has at most heights, and lines L6 to L8 scan at most rectangles per height, after one sort of by . So one placement takes time, and all of them take time. The extra space is . Chazelle (1983) keeps the free space as a structure of empty regions and places all rectangles in time and linear space. These bounds are for the rule itself. They say nothing about the height it reaches.
For polygons with at most vertices each, the cost is dominated by the no-fit polygons and their arrangement. A placement must look at all pairs of edges of up to no-fit polygons, so a simple implementation is quadratic in the total number of their edges per part.
Properties
What is proved:
- Lexicographic optimality per part. Each rectangle gets the least feasible given the earlier ones. This is not optimality of the packing.
- Ratio 3 for decreasing widths. If the rectangles are sorted by decreasing width, the height is at most (Baker, Coffman and Rivest 1980). For other orders, such as increasing widths, the ratio is not bounded by any constant.
- No order is always optimal. Brown (1980) gave instances where no order of the rectangles lets BL reach the optimum. Hougardy and Zondervan (STACS 2026) found an order with ratio , the first order that beats 3 since 1980.
- Online in the order. A part is placed without looking at the parts after it.
- Exact. With integer or rational sizes, positions and tests are exact.
What is only measured: the quality of BLF inside a search over orders, for example by a genetic algorithm or simulated annealing. Hopper and Turton (2001) and Burke, Hellier, Kendall and Whitwell (2006) report densities on benchmark sets from the literature. These are empirical results. They carry no bound.
Variants and improvements
- Sliding bottom-left (Jakobs 1996). Start the part at the top right, then move it down as far as it goes, then left as far as it goes, and repeat until it cannot move. The result is a position that is locally stuck. It need not be the lowest one, and it cannot enter a closed hole. Hopper and Turton (2001) call this rule BL and the hole-filling rule of this page BLF.
- Polygons with no-fit polygons. For a part with reference point , the feasible positions are the points of the inner-fit polygon of the sheet that are in the interior of no no-fit polygon of with a placed part. The least point in is a vertex of this region: a vertex of a no-fit polygon or of the inner-fit polygon, or a crossing of two of their edges. Dowsland, Vaid and Dowsland (2002) compute this position, holes included. The predicates are orientation tests and segment intersection tests, and in exact arithmetic the crossing points are rationals.
- Rotations. Many nesting codes allow a few fixed angles, for example the multiples of 90 degrees, and keep the best position over the angles. Each angle needs its own no-fit polygons.
- Direct overlap resolution. Burke, Hellier, Kendall and Whitwell (2006) do not build no-fit polygons. They move the part from a start position and resolve overlaps with the placed parts edge by edge, also for arcs.
- Order search. The rule is a decoder. A search over the order of the parts, by local search, a genetic algorithm or simulated annealing, calls it once per candidate order. Sorting by decreasing width, height or area gives the usual start.
- Raster version. On a grid of pixels, the parts and the sheet are bitmaps, and a scan of the cells finds the first cell where the part fits. It is easy and robust, but its precision is the cell size.
When to use it
Use BLF when parts arrive in a fixed order, or as the inner step of a search over orders, in sheet metal, wood, glass, textile and laser cutting. It is simple, exact with integer coordinates, and it fills holes that simpler rules leave. If you need a guaranteed height for rectangles, use a method with a proved bound, as on the strip packing page. If the parts are rectangles that must be cut with straight cuts across the sheet, the packing must be a guillotine packing, and BLF does not respect that (see guillotine cuts).
Pitfalls
- Sliding is not filling. Code that pushes a part down and left finds a stuck position, not the lowest feasible one. In the example the sliding rule puts at height 6 instead of 1, and the packing is 9 high instead of 6.
- The order matters most. With increasing widths the height can be arbitrarily far from the optimum. Sort first, or search over orders.
- Floating point gaps. A part that fits a gap exactly can be rejected, or it can overlap a neighbour by . Use integer units or exact rationals for the tests, and floats only for display.
- Touching versus overlapping. The overlap test must use the interiors. A closed-set test rejects parts that only touch and leaves a thin gap at every edge.
- Candidates for polygons. The least position of a polygon is often at a crossing of edges of two different no-fit polygons. A code that tests only the vertices of each no-fit polygon misses it.
- Holes in no-fit polygons. A no-fit polygon of a part with a cavity can have holes. They are feasible regions, and a code that keeps only the outer boundary loses them.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bottom-left-fill/. The authors are listed in prov/28CHNP.jsonl.
"""Bottom-left fill of rectangles in a strip of fixed width.
Each rectangle, in the given order, goes to the feasible position (x, y) that
is lexicographically least in (y, x): first as low as possible, then as far
left as possible at that height. Positions inside holes between earlier
rectangles count, which is what "fill" means. For rectangles this is the
bottom-left rule of Baker, Coffman and Rivest (1980).
Input: the strip width W and a list of (w, h) pairs, with 0 < w <= W and h > 0.
Sizes may be int or Fraction. Output: a list of (x, y) lower-left corners, one
per rectangle, in input order. Two rectangles overlap when their interiors
meet; touching edges are allowed. Every test is a comparison of input sums,
so the result is exact for int and Fraction input.
"""
def place_one(width, placed, w, h):
"""Return the bottom-left position (x, y) of a w by h rectangle.
placed is a list of (x, y, w, h) rectangles that do not overlap.
"""
by_x = sorted(placed) # sorted by the left edge x
heights = sorted({0} | {py + ph for (_, py, _, ph) in placed}) # @line L3
for y in heights: # @line L4
x = 0 # @line L5
for (px, py, pw, ph) in by_x: # @line L6
if not (py < y + h and py + ph > y):
continue # not in the band of heights (y, y + h)
if px >= x + w: # @line L7
break # @line L7
x = max(x, px + pw) # @line L8
if x + w <= width: # @line L9
return x, y # @line L10
raise AssertionError("unreachable: the highest top always has a free row")
def bottom_left_fill(width, rects):
"""Place the rectangles in order and return their lower-left corners."""
for (w, h) in rects:
if not (0 < w <= width and h > 0):
raise ValueError("each rectangle needs 0 < w <= width and h > 0")
placed = [] # @line L1
out = []
for (w, h) in rects: # @line L2
x, y = place_one(width, placed, w, h)
placed.append((x, y, w, h)) # @line L10
out.append((x, y))
return out # @line L11
def overlap(a, b):
"""True when the interiors of the rectangles a and b, as (x, y, w, h), meet."""
ax, ay, aw, ah = a
bx, by, bw, bh = b
return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
def strip_height(rects, positions):
"""Height of the packing: the highest top edge, or 0 when empty."""
return max((y + h for (w, h), (x, y) in zip(rects, positions)), default=0)
test_bottom_left_fill.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bottom-left-fill/. The authors are listed in prov/28CHNP.jsonl.
import random
from fractions import Fraction
import pytest
from bottom_left_fill import bottom_left_fill, overlap, place_one, strip_height
def brute_place(width, placed, w, h):
"""Least (y, x) over every integer position, by a direct overlap test."""
top = sum(ph for (_, _, _, ph) in placed)
for y in range(top + 1):
for x in range(width - w + 1):
r = (x, y, w, h)
if not any(overlap(r, p) for p in placed):
return x, y
raise AssertionError("no position found")
def check_packing(width, rects, pos):
boxes = [(x, y, w, h) for (w, h), (x, y) in zip(rects, pos)]
for (x, y, w, h) in boxes:
assert 0 <= x and x + w <= width and 0 <= y
for i in range(len(boxes)):
for j in range(i):
assert not overlap(boxes[i], boxes[j])
def test_example():
rects = [(2, 4), (6, 1), (2, 4), (10, 2), (5, 3)]
pos = bottom_left_fill(10, rects)
assert pos == [(0, 0), (2, 0), (8, 0), (0, 4), (2, 1)]
assert strip_height(rects, pos) == 6
check_packing(10, rects, pos)
def test_small_cases():
assert bottom_left_fill(5, []) == []
assert bottom_left_fill(5, [(5, 1)]) == [(0, 0)]
assert bottom_left_fill(4, [(2, 1)] * 4) == [(0, 0), (2, 0), (0, 1), (2, 1)]
# touching edges are allowed, so the second square sits right next to the first
assert bottom_left_fill(2, [(1, 1), (1, 1), (2, 1)]) == [(0, 0), (1, 0), (0, 1)]
with pytest.raises(ValueError):
bottom_left_fill(3, [(4, 1)])
with pytest.raises(ValueError):
bottom_left_fill(3, [(1, 0)])
def test_hole_is_filled():
# a lid on two posts leaves a closed hole; the last rectangle goes into it
rects = [(1, 3), (3, 1), (1, 3), (5, 1), (1, 2)]
pos = bottom_left_fill(5, rects)
assert pos[:4] == [(0, 0), (1, 0), (4, 0), (0, 3)]
assert pos[4] == (1, 1)
check_packing(5, rects, pos)
def test_against_brute_force():
rng = random.Random(28)
for _ in range(400):
width = rng.randint(2, 8)
n = rng.randint(1, 7)
rects = [(rng.randint(1, width), rng.randint(1, 4)) for _ in range(n)]
pos = bottom_left_fill(width, rects)
check_packing(width, rects, pos)
placed = []
for (w, h), p in zip(rects, pos):
assert p == brute_place(width, placed, w, h)
placed.append((p[0], p[1], w, h))
def test_fractions_scale():
rng = random.Random(7)
s = Fraction(2, 3)
for _ in range(100):
width = rng.randint(2, 7)
rects = [(rng.randint(1, width), rng.randint(1, 3)) for _ in range(rng.randint(1, 6))]
pos = bottom_left_fill(width, rects)
pos_s = bottom_left_fill(width * s, [(w * s, h * s) for (w, h) in rects])
assert pos_s == [(x * s, y * s) for (x, y) in pos]
def test_place_one_is_lowest_then_leftmost():
rng = random.Random(3)
for _ in range(200):
width = rng.randint(3, 8)
placed = []
for (w, h) in [(rng.randint(1, width), rng.randint(1, 3)) for _ in range(5)]:
x, y = place_one(width, placed, w, h)
# no feasible integer position is lower, or as low and further left
for yy in range(y + 1):
for xx in range(width - w + 1):
if (yy, xx) < (y, x):
assert any(overlap((xx, yy, w, h), p) for p in placed)
placed.append((x, y, w, h))
History
Baker, Coffman and Rivest defined the bottom-left rule for rectangles in a strip in 1980, as part of the first worst-case analysis of two-dimensional packing heuristics, and proved the bound 3 for decreasing widths. Chazelle gave an implementation in 1983. In the 1990s the rule moved to irregular shapes in operations research. Jakobs (1996) used the sliding rule inside a genetic algorithm, and Liu and Teng (1999) improved the sliding moves. Hopper and Turton (2001) compared the sliding rule with the hole-filling rule. Dowsland, Vaid and Dowsland (2002) computed the bottom-left position of polygons, holes included, with no-fit polygons, and Burke, Hellier, Kendall and Whitwell (2006) gave a hole-filling rule for parts with lines and arcs. In 2025 Hougardy and Zondervan found the first order of the rectangles with a better ratio than 3.
References
- Brenda S. Baker, Edward G. Coffman Jr. and Ronald L. Rivest, Orthogonal packings in two dimensions, SIAM Journal on Computing 9(4), 1980, 846 to 855, the bottom-left rule, the bound of 3 times the optimum for decreasing widths, and the orders for which the rule is arbitrarily bad
- Bernard Chazelle, The bottomn-left bin-packing heuristic, an efficient implementation, IEEE Transactions on Computers C-32(8), 1983, 697 to 707, the O(n^2) time and linear space implementation for rectangles (the title has this spelling in print)
- Stefan Jakobs, On genetic algorithms for the packing of polygons, European Journal of Operational Research 88(1), 1996, 165 to 181, the sliding bottom-left rule (down, then left, repeated) and the genetic search over the order
- E. Hopper and B. C. H. Turton, An empirical investigation of meta-heuristic and heuristic algorithms for a 2D packing problem, European Journal of Operational Research 128(1), 2001, 34 to 57, the comparison of the sliding BL rule and the bottom-left fill rule, alone and inside genetic search, simulated annealing and naive evolution
- Kathryn A. Dowsland, Subodh Vaid and William B. Dowsland, An algorithm for polygon placement using a bottom-left strategy, European Journal of Operational Research 141(2), 2002, 371 to 381, the bottom-left position of a polygon, holes included, from no-fit polygons
- Edmund K. Burke, Robert S. R. Hellier, Graham Kendall and Glenn Whitwell, A new bottom-left-fill heuristic algorithm for the two-dimensional irregular packing problem, Operations Research 54(3), 2006, 587 to 601, bottom-left fill of polygons with lines and arcs by direct overlap resolution, with a search over the order
- Stefan Hougardy and Bart Zondervan, A 13/6-approximation for strip packing via the bottom-left algorithm, STACS 2026, LIPIcs, article 54, a new order of the rectangles for which the bottom-left rule has ratio 13/6
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 28CHNP Edit this page History Report an error Markdown