Algorithmadvanced
Hirschberg-Larmore algorithm
Also called concave least weight subsequence algorithm.
Solve the least weight subsequence problem with a concave weight in O(n log n) time with a queue of candidates and binary search.
- Time
- O(n log n) worst
- Space
- Θ(n) extra
- Where
- n = the last index of the problem (the number of values F(1) to F(n))
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel S. Hirschberg, Lawrence L. Larmore, 1987
The Hirschberg-Larmore algorithm solves the least weight subsequence problem , in time when the weight is concave, that is, when it satisfies the quadrangle inequality. The plain dynamic program tries every earlier index for every and takes time. The concave condition gives the earlier indices a simple structure: each one is the best last break for an interval of targets , and the intervals are in the order of the indices. The algorithm keeps these intervals in a deque, reads from its front, and places each new index at the back with a binary search. Daniel Hirschberg and Lawrence Larmore gave it in 1987, with line breaking as the main application. Wilber's algorithm later reduced the time to .
In plain words
You compute the best cost for each position from left to right. Each earlier position is a candidate for the last step before .
The concave condition says this: if a later candidate is at least as good as an earlier one at some target, it stays at least as good at every later target. So an old candidate, once beaten, never comes back.
Hence each candidate is the best one for a run of targets, and the runs come in the order of the candidates. Keep a list of the runs. The front of the list gives . A new candidate takes over a final run of targets: remove the runs at the back that it wins completely, and find where its own run starts by binary search.
The problem
The input is an integer and a weight for , given by a procedure that returns any weight in time. The weight must satisfy
the condition that Hirschberg and Larmore call concave. The weight is allowed for a pair that may not be used, such as a line that is too long, if the infinite pairs are closed under lengthening: when , also for all and . The output is and, for each , an index that attains the minimum. Following back from gives an optimal subsequence.
The algorithm
Write for the cost of reaching with as the last break. The queue holds pairs : the candidate is the best of all candidates so far for the targets from up to the start of the next pair.
HIRSCHBERG-LARMORE(n, w)- 1
F[0] ← 0; F[1..n] ← ∞ - 2
Q ← a deque that holds the pair (0, 1) - 3
for j ← 1 to n do - 4
while Q has a second pair (c', s') with s' ≤ j do remove the front pair - 5
(c, s) ← the front pair; F[j] ← g_c(j); P[j] ← c; if j = n then stop - 6
while Q is not empty do (c, s) ← the back pair; s ← max(s, j + 1)- 7
if g_j(s) ≤ g_c(s) then remove the back pair; continue - 8
binary search for the least t in s + 1 .. n with g_j(t) ≤ g_c(t), or t = n + 1 if there is none - 9
if t ≤ n then append (j, t) at the back stop this loop- 10
if Q is empty then append (j, j + 1) return F, P
Line L4 drops the candidates whose run ended before . Line L5 reads the answer for from the front, which owns . Lines L6 to L10 add as a candidate for the targets after . Line L7 removes a back candidate that already beats at the first target of its run, because then beats it on the whole run. Line L8 searches in the run of the first back candidate that survives, where the test " is at least as good" is false and then true, so binary search finds the point where it changes. If never wins (line L9 with ), it is not stored at all.
Example
Take and , the check value of the least weight subsequence page. The table shows each step: the pairs that line L4 drops at the front, the values set by line L5, the pairs that line L7 removes at the back, and the queue at the end of the step.
| front drops | back removals | queue after the step | |||
|---|---|---|---|---|---|
| 1 | 4 | 0 | (0, 1), (1, 6) | ||
| 2 | 1 | 0 | (1, 6) | (0, 1), (2, 5) | |
| 3 | 0 | 0 | (2, 5) | (0, 1), (3, 5) | |
| 4 | 1 | 0 | (0, 1), (3, 5), (4, 7) | ||
| 5 | (0, 1) | 1 | 3 | (3, 5), (4, 7), (5, 8) | |
| 6 | 0 | 3 | (5, 8) | (3, 5), (4, 7), (6, 8) | |
| 7 | (3, 5) | 1 | 4 | (4, 7), (6, 8), (7, 10) | |
| 8 | (4, 7) | 1 | 6 | (6, 8), (7, 10) | |
| 9 | 0 | 6 | (6, 8), (7, 10) | ||
| 10 | (6, 8) | 1 | 7 | (7, 10) |
At step 1 the new candidate 1 loses to 0 at target 2 ( against ), and the binary search over finds that it wins from target 6 on (, but ). At step 2 the candidate 2 beats 1 at target 6, so line L7 removes , and the search against 0 gives the start 5. At steps 8 and 9 the new candidate never wins, so it is not stored. The values are the ones of the dynamic program, and the back pointers give , the subsequence 0, 4, 7, 10 with weight . The dynamic program, which keeps the first minimizer, gives 0, 3, 6, 10 with the same weight; both are optimal.
Correctness
The proof rests on one lemma. Let . If , then : adding to both sides of the inequality with the four indices gives . The closure of the infinite pairs makes the four values finite whenever is finite. From the lemma, the targets where a new candidate is at least as good as all earlier candidates form a final interval or the empty set.
The invariant is that at the start of step , the queue lists the candidates in increasing order with increasing starts, the front start is at most , and for every target , the candidate of the last pair whose start is at most attains . Line L4 keeps this and makes the front own , so line L5 sets . Lines L6 to L10 cut the old runs at and append : a removed back candidate has all its targets in the final interval, and the binary search is on a monotone test, so it returns . So the invariant holds for . The full proof is in the proof file.
Proof: The queue of candidates gives the least weight subsequence for a concave weightfull
Claim. Let and let , for , take values in the reals or . Assume the inequality
whenever all four values are finite (this is the condition that Hirschberg and Larmore call concave; it is the quadrangle inequality of a Monge array), and assume that the infinite values are closed under lengthening: if then for all and . Then HIRSCHBERG-LARMORE (lines L1 to L10) stops and returns for , where and , and . It uses evaluations of .
Setup. For write , the cost of reaching with as the last break. For a step and a target , let , the best value at over the candidates . So .
Lemma 1 (a later candidate that wins keeps winning). Let . If , then .
Proof. If there is nothing to show. Otherwise and are finite. By the closure, , and are finite too: each pair , , has its first index and its second index, so if its value were infinite, would be infinite. Then is finite, so makes finite. All four values of the inequality are finite, and adding to both sides gives , that is .
Lemma 2 (the new candidate wins on a final interval). Fix and let , the targets where the new candidate is at least as good as all earlier ones. If and , then . So is empty or for some .
Proof. Take any . Then , and Lemma 1 with and gives . This holds for every , so .
Invariant. At the start of step (line L3), the queue holds pairs with , , and , and
(Q) for every with , the candidate with has .
We say that owns the targets with (with ).
Initialization. For the queue is (line L2), and the only candidate is 0.
Maintenance, the value. Line L4 drops the front while . A dropped owns no target , because , so (Q) still holds, and now . Hence owns and line L5 sets , with a minimizer.
Maintenance, the new candidate. If the loop ends. Otherwise the step must make (Q) hold for , where the candidates are and . By Lemma 2, attains this minimum exactly on , a final interval or the empty set, and the old owner attains it on the rest. So the right queue is the old one with the owners cut off at , followed by .
Lines L6 to L9 build this queue. Look at the back pair and let ; the back candidate owns all of . Line L7 compares with .
- If , then , so by Lemma 2 all targets from to are in , and is no longer needed for any target : every target it owns is at least , or below . Line L7 drops it. The new back pair now owns up to , and on the targets it did not own before, wins anyway, so the argument repeats with the new back pair.
- Otherwise , so . On the back candidate owns every target, so for the test is the test , which is false and then true by Lemma 2. The binary search of line L8 keeps the invariant that every in its range is not in and every in the range is in , or ; it stops with , the least element of , or when is empty. Line L9 appends when .
- If every pair is dropped, then : the last dropped pair was the front, with . Line L10 appends .
In all cases the new queue is the right one. The order conditions hold: , and the new start is larger than the of the last kept pair, since . The front start is at most : either the front is unchanged with , or it is . So the invariant holds at the start of step .
Termination. The outer loop runs times. Each pass of line L4 or of the loop at line L6 drops a pair, each candidate enters the queue at most once, so there are fewer than drops in all, and each binary search makes at most steps.
Conclusion. By the maintenance step, and is a minimizer for every , and by line L1. Each step evaluates once in line L5, twice for each dropped pair, and twice per step of the binary search, so the total is .
Why the closure is needed. If an infinite value sits inside a finite region, Lemma 1 can fail. Take for one pair and finite values around it: the later candidate can win at and lose at only because of the hole. The binary search then reads a test that is not monotone and can return the wrong start.
Complexity
Each candidate enters the queue at most once and leaves at most once, so lines L4 and L7 remove fewer than pairs in all. Each step evaluates once in line L5, twice for each removed pair, twice at line L7 for the pair that survives, and twice for each step of a binary search over at most targets. So the number of evaluations is at most about , and the time is . The space is for , and the queue.
Measured with the kind of weights that the tests of this page use, random concave weights of the form for a convex , the program makes about evaluations for , for , for and for : the count per index grows by about 4 each time grows by a factor of 4, as predicts. On with it makes 21588 evaluations, while the dynamic program makes .
Properties
- Values in order. It finds in this order, and is final at step .
- Not online in the weights. At step it reads for targets up to , so all weights must be known in advance. For line breaking with prefix sums this is no problem.
- Exact. It uses only comparisons and additions of values of and , so with exact numbers, such as integers or fractions, the values are exact.
- Ties. The test at lines L7 and L8 lets a later candidate win a tie. The value is the same, but the back pointers can give another optimal subsequence than the dynamic program, as in the example.
Variants and improvements
- Linear time. Wilber's algorithm uses the matrix searching of SMAWK on blocks of targets and takes time. Galil and Park gave a simpler method in 1990.
- The reverse inequality. If satisfies the inequality with , a later candidate that wins can lose again later, the runs are no longer in the order of the candidates, and the queue method fails. Other methods are needed, and the best known ones take almost linear time (see the least weight subsequence page).
- Linear cost per candidate. If is a linear function of a value of for each fixed , the convex hull trick finds the minima with a hull of lines. The queue of runs is the same idea for any weight with the quadrangle inequality.
- Layers. For a fixed number of parts, each layer of the dynamic program is a matrix whose row minima can be found by the divide and conquer optimization in per layer, or by SMAWK in .
- Free last line. When the last line of a paragraph costs nothing, the weight to breaks the inequality. Run the algorithm up to with the concave weight, then take in one more pass.
When to use it
Use it for a dynamic program of the form whose weight satisfies the quadrangle inequality, such as line breaking with rigid spaces and a convex cost of the slack, as in printing neatly, or splitting a sequence into blocks with a convex cost of the block size. It is short and simple, and its factor is small in practice. For the strict bound use Wilber's algorithm, which is more complex. For the demerits of Knuth-Plass line breaking, which depend on more than the two ends of a line, it does not apply directly.
Pitfalls
- Check the inequality. The method gives wrong answers, with no error, for a weight that is not concave. The test
test_not_concave_can_failshows a weight that is small only for jumps of length 1 and 4, where the program differs from the dynamic program. The capped badness of TeX is not concave either. - Concave or convex. Papers use both words for the same inequality. Check the inequality itself, not the name.
- Infinite weights in a hole. An infinite weight is safe only when the infinite pairs are closed under lengthening, as for lines that are too long. A single forbidden pair inside a region of finite weights can break the monotone test of the binary search.
- The range of the search. The search must start after , because targets at or before are already done. The program also must not append a pair whose start is beyond .
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/hirschberg-larmore-algorithm/. The authors are listed in prov/HFGGSH.jsonl.
"""The least weight subsequence problem for a concave weight, in O(n log n).
F(0) = 0 and F(j) = min over 0 <= i < j of F(i) + w(i, j), for j = 1 .. n.
The weight w is concave in the sense of Hirschberg and Larmore:
w(i, j) + w(i', j') <= w(i, j') + w(i', j) for all i <= i' < j <= j'.
(This is the quadrangle inequality of a Monge array; some authors call it
convex.) Then a later candidate that is at least as good as an earlier one
at some j stays at least as good at every later j. So each candidate i is
the best one for an interval of j, and the intervals are in the order of
the candidates. A queue holds the live candidates with the first j of
their interval. A new candidate removes the candidates at the back that it
beats on their whole interval, and finds the start of its own interval by
binary search.
w may return math.inf for a pair (i, j) that is not allowed, if the pairs
with an infinite weight are closed under making the interval longer: if
w(i, j) is infinite, so is w(i', j') for all i' <= i and j' >= j. A line
that is too long for the measure is the usual case.
"""
import math
from collections import deque
from typing import Callable, List, Optional, Tuple
Weight = Callable[[int, int], float]
def lws_dp(n: int, w: Weight, stats: Optional[dict] = None) -> Tuple[List, List[int]]:
"""The O(n^2) dynamic program. Returns F[0..n] and the best predecessor P[1..n]."""
F = [0] + [math.inf] * n
P = [0] * (n + 1)
evals = 0
for j in range(1, n + 1):
for i in range(j):
evals += 1
v = F[i] + w(i, j)
if v < F[j]:
F[j], P[j] = v, i
if stats is not None:
stats["evals"] = evals
return F, P
def hirschberg_larmore(n: int, w: Weight, stats: Optional[dict] = None) -> Tuple[List, List[int]]:
"""F[0..n] and P[1..n] for a concave w, with O(n log n) evaluations of w."""
evals = 0
def g(i: int, j: int):
nonlocal evals
evals += 1
return F[i] + w(i, j)
F = [0] + [math.inf] * n # @line L1
P = [0] * (n + 1)
Q = deque([(0, 1)]) # (candidate i, first j of its interval) # @line L2
for j in range(1, n + 1): # @line L3
while len(Q) >= 2 and Q[1][1] <= j: # @line L4
Q.popleft()
i = Q[0][0]
F[j], P[j] = g(i, j), i # @line L5
if j == n:
break
while Q: # @line L6
i, s = Q[-1]
s = max(s, j + 1)
if g(j, s) <= g(i, s): # @line L7
Q.pop() # j is at least as good on all of the interval of i
continue
lo, hi = s + 1, n + 1 # @line L8
while lo < hi: # find the least c in s+1 .. n where j beats i
mid = (lo + hi) // 2
if g(j, mid) <= g(i, mid):
hi = mid
else:
lo = mid + 1
if lo <= n:
Q.append((j, lo)) # @line L9
break
if not Q:
Q.append((j, j + 1)) # @line L10
if stats is not None:
stats["evals"] = evals
return F, P
def breaks(P: List[int], n: int) -> List[int]:
"""The chosen indices i_1 < ... < i_k = n, read back from the predecessors."""
out = []
j = n
while j > 0:
out.append(j)
j = P[j]
return out[::-1]
test_hirschberg_larmore_algorithm.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hirschberg-larmore-algorithm/. The authors are listed in prov/HFGGSH.jsonl.
import math
import random
from fractions import Fraction
from hirschberg_larmore_algorithm import breaks, hirschberg_larmore, lws_dp
def concave_weight(rng, n, line=None):
"""w(i, j) = f(S_j - S_i - l) + a(i) + b(j) with f convex: concave in the sense of the page."""
widths = [rng.randint(1, 6) for _ in range(n)]
S = [0]
for x in widths:
S.append(S[-1] + x)
a = [rng.randint(0, 20) for _ in range(n + 1)]
b = [rng.randint(0, 20) for _ in range(n + 1)]
l = rng.randint(5, 30)
kind = rng.randrange(3)
def w(i, j):
d = S[j] - S[i] - l
if line is not None and S[j] - S[i] > line:
return math.inf
if kind == 0:
f = d * d
elif kind == 1:
f = abs(d) ** 3
else:
f = max(0, d) * 7 + max(0, -d)
return f + a[i] + b[j]
return w
def quadrangle_holds(n, w):
for i in range(n + 1):
for i2 in range(i, n + 1):
for j in range(max(i2, i + 1), n + 1):
for j2 in range(j, n + 1):
if i2 >= j:
continue
if w(i, j) + w(i2, j2) > w(i, j2) + w(i2, j):
return False
return True
def test_check_value():
w = lambda i, j: (j - i - 3) ** 2
F, P = hirschberg_larmore(10, w)
assert F == [0, 4, 1, 0, 1, 1, 0, 1, 1, 0, 1]
assert F[10] == 1
assert F == lws_dp(10, w)[0]
assert sum(w(i, j) for i, j in zip([0] + breaks(P, 10), breaks(P, 10))) == F[10]
assert breaks(P, 10) in ([3, 6, 10], [3, 7, 10], [4, 7, 10])
assert breaks(lws_dp(10, w)[1], 10) == [3, 6, 10]
def test_weights_used_are_concave():
rng = random.Random(5)
for _ in range(20):
n = rng.randint(1, 12)
assert quadrangle_holds(n, concave_weight(rng, n))
def test_matches_dynamic_program():
rng = random.Random(1987)
for _ in range(150):
n = rng.randint(1, 60)
w = concave_weight(rng, n)
F, P = hirschberg_larmore(n, w)
G, _ = lws_dp(n, w)
assert F == G
b = breaks(P, n)
assert sum(w(i, j) for i, j in zip([0] + b, b)) == F[n]
def test_fractions_and_ties():
rng = random.Random(7)
for _ in range(60):
n = rng.randint(1, 30)
c = Fraction(rng.randint(1, 5), rng.randint(1, 5))
w = lambda i, j, c=c: c * (j - i - 2) ** 2 # many ties
assert hirschberg_larmore(n, w)[0] == lws_dp(n, w)[0]
def test_lines_that_are_too_long():
rng = random.Random(11)
for _ in range(100):
n = rng.randint(1, 50)
w = concave_weight(rng, n, line=rng.randint(6, 30))
F, _ = hirschberg_larmore(n, w)
G, _ = lws_dp(n, w)
assert F == G
def test_not_concave_can_fail():
# w(i, j) is small only for j - i = 1 or j - i = 4: not concave, and the method is wrong
w = lambda i, j: 0 if j - i == 4 else (1 if j - i == 1 else 10)
assert not quadrangle_holds(8, w)
found = False
for n in range(1, 13):
if hirschberg_larmore(n, w)[0] != lws_dp(n, w)[0]:
found = True
assert found
def test_evaluations_are_n_log_n():
rng = random.Random(3)
for n in (256, 1024, 4096):
w = concave_weight(rng, n)
st = {}
hirschberg_larmore(n, w, st)
assert st["evals"] <= 4 * n * math.log2(n)
History
Hirschberg and Larmore defined the least weight subsequence problem in a paper in SIAM Journal on Computing in 1987, named the concave condition, and gave the algorithm, with the breaking of paragraphs into lines as the main application. Wilber reduced the time to in 1988 by applying the matrix searching of Aggarwal, Klawe, Moran, Shor and Wilber, and Galil and Park gave a simpler linear method in 1990.
References
- D. S. Hirschberg and L. L. Larmore, The least weight subsequence problem, SIAM Journal on Computing 16(4), 628-638, 1987, the definition of the problem, the concave condition and the O(n log n) algorithm
- Robert Wilber, The concave least-weight subsequence problem revisited, Journal of Algorithms 9(3), 418-425, 1988, the O(n) algorithm that improves on the O(n log n) bound
- Zvi Galil and Kunsoo Park, A linear-time algorithm for concave one-dimensional dynamic programming, Information Processing Letters 33(6), 309-311, 1990, a simpler O(n) algorithm for the same problem
Where this leads
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 HFGGSH Edit this page History Report an error Markdown