Algorithm Search⌘K

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))
Properties
deterministicofflineiterative
Origin
Daniel S. Hirschberg, Lawrence L. Larmore, 1987

The Hirschberg-Larmore algorithm solves the least weight subsequence problem F(0)=0F(0) = 0, F(j)=min⁡i<j(F(i)+w(i,j))F(j) = \min_{i < j} \bigl( F(i) + w(i, j) \bigr) in O(nlog⁡n)O(n \log n) time when the weight ww is concave, that is, when it satisfies the quadrangle inequality. The plain dynamic program tries every earlier index for every jj and takes Θ(n2)\Theta(n^2) time. The concave condition gives the earlier indices a simple structure: each one is the best last break for an interval of targets jj, and the intervals are in the order of the indices. The algorithm keeps these intervals in a deque, reads F(j)F(j) 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 O(n)O(n).

In plain words

You compute the best cost F(j)F(j) for each position jj from left to right. Each earlier position ii is a candidate for the last step before jj.

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 F(j)F(j). 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 n≥1n \ge 1 and a weight w(i,j)w(i, j) for 0≤i<j≤n0 \le i < j \le n, given by a procedure that returns any weight in O(1)O(1) time. The weight must satisfy

w(i,j)+w(i′,j′)≤w(i,j′)+w(i′,j)for all 0≤i≤i′<j≤j′≤n,w(i, j) + w(i', j') \le w(i, j') + w(i', j) \qquad \text{for all } 0 \le i \le i' < j \le j' \le n,

the condition that Hirschberg and Larmore call concave. The weight +∞+\infty 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 w(i,j)=+∞w(i, j) = +\infty, also w(i′′,j′′)=+∞w(i'', j'') = +\infty for all i′′≤ii'' \le i and j′′≥jj'' \ge j. The output is F(0),…,F(n)F(0), \ldots, F(n) and, for each j≥1j \ge 1, an index P(j)<jP(j) < j that attains the minimum. Following PP back from nn gives an optimal subsequence.

The algorithm

Write gi(j)=F(i)+w(i,j)g_i(j) = F(i) + w(i, j) for the cost of reaching jj with ii as the last break. The queue QQ holds pairs (c,s)(c, s): the candidate cc is the best of all candidates so far for the targets from ss up to the start of the next pair.

  1. HIRSCHBERG-LARMORE(n, w)
  2. 1F[0] ← 0; F[1..n] ← ∞
  3. 2Q ← a deque that holds the pair (0, 1)
  4. 3for j ← 1 to n do
  5. 4while Q has a second pair (c', s') with s' ≤ j do remove the front pair
  6. 5(c, s) ← the front pair; F[j] ← g_c(j); P[j] ← c; if j = n then stop
  7. 6while Q is not empty do
  8. (c, s) ← the back pair; s ← max(s, j + 1)
  9. 7if g_j(s) ≤ g_c(s) then remove the back pair; continue
  10. 8binary search for the least t in s + 1 .. n with g_j(t) ≤ g_c(t), or t = n + 1 if there is none
  11. 9if t ≤ n then append (j, t) at the back
  12. stop this loop
  13. 10if Q is empty then append (j, j + 1)
  14. return F, P

Line L4 drops the candidates whose run ended before jj. Line L5 reads the answer for jj from the front, which owns jj. Lines L6 to L10 add jj as a candidate for the targets after jj. Line L7 removes a back candidate that jj already beats at the first target of its run, because then jj beats it on the whole run. Line L8 searches in the run of the first back candidate that survives, where the test "jj is at least as good" is false and then true, so binary search finds the point where it changes. If jj never wins (line L9 with t=n+1t = n + 1), it is not stored at all.

Example

Take n=10n = 10 and w(i,j)=(j−i−3)2w(i, j) = (j - i - 3)^2, 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.

jj front drops F(j)F(j) P(j)P(j) 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 (g1(2)=4+4=8g_1(2) = 4 + 4 = 8 against g0(2)=1g_0(2) = 1), and the binary search over 3,…,103, \ldots, 10 finds that it wins from target 6 on (g1(6)=8≤g0(6)=9g_1(6) = 8 \le g_0(6) = 9, but g1(5)=5>g0(5)=4g_1(5) = 5 > g_0(5) = 4). At step 2 the candidate 2 beats 1 at target 6, so line L7 removes (1,6)(1, 6), 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 FF are the ones of the dynamic program, and the back pointers give 10→7→4→010 \to 7 \to 4 \to 0, the subsequence 0, 4, 7, 10 with weight 1+0+0=11 + 0 + 0 = 1. 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 i<i′<j≤j′i < i' < j \le j'. If gi′(j)≤gi(j)g_{i'}(j) \le g_i(j), then gi′(j′)≤gi(j′)g_{i'}(j') \le g_i(j'): adding F(i)+F(i′)F(i) + F(i') to both sides of the inequality with the four indices i≤i′<j≤j′i \le i' < j \le j' gives gi′(j′)−gi(j′)≤gi′(j)−gi(j)≤0g_{i'}(j') - g_i(j') \le g_{i'}(j) - g_i(j) \le 0. The closure of the infinite pairs makes the four values finite whenever gi(j′)g_i(j') is finite. From the lemma, the targets where a new candidate jj is at least as good as all earlier candidates form a final interval {d,…,n}\{d, \ldots, n\} or the empty set.

The invariant is that at the start of step jj, the queue lists the candidates in increasing order with increasing starts, the front start is at most jj, and for every target j′≥jj' \ge j, the candidate of the last pair whose start is at most j′j' attains min⁡i<jgi(j′)\min_{i < j} g_i(j'). Line L4 keeps this and makes the front own jj, so line L5 sets F[j]=F(j)F[j] = F(j). Lines L6 to L10 cut the old runs at dd and append (j,d)(j, d): a removed back candidate has all its targets in the final interval, and the binary search is on a monotone test, so it returns dd. So the invariant holds for j+1j + 1. The full proof is in the proof file.

Proof: The queue of candidates gives the least weight subsequence for a concave weightfull

Claim. Let n≥1n \ge 1 and let w(i,j)w(i, j), for 0≤i<j≤n0 \le i < j \le n, take values in the reals or +∞+\infty. Assume the inequality

w(i,j)+w(i′,j′)≤w(i,j′)+w(i′,j)for all i≤i′<j≤j′,w(i, j) + w(i', j') \le w(i, j') + w(i', j) \qquad \text{for all } i \le i' < j \le j',

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 w(i,j)=+∞w(i, j) = +\infty then w(i′′,j′′)=+∞w(i'', j'') = +\infty for all i′′≤ii'' \le i and j′′≥jj'' \ge j. Then HIRSCHBERG-LARMORE (lines L1 to L10) stops and returns F[j]=F(j)F[j] = F(j) for j=0,…,nj = 0, \ldots, n, where F(0)=0F(0) = 0 and F(j)=min⁡0≤i<j(F(i)+w(i,j))F(j) = \min_{0 \le i < j} (F(i) + w(i, j)), and F[P[j]]+w(P[j],j)=F(j)F[P[j]] + w(P[j], j) = F(j). It uses O(nlog⁡n)O(n \log n) evaluations of ww.

Setup. For i<ji < j write gi(j)=F(i)+w(i,j)g_i(j) = F(i) + w(i, j), the cost of reaching jj with ii as the last break. For a step jj and a target j′≥jj' \ge j, let bestj(j′)=min⁡i<jgi(j′)\mathrm{best}_j(j') = \min_{i < j} g_i(j'), the best value at j′j' over the candidates 0,…,j−10, \ldots, j - 1. So F(j)=bestj(j)F(j) = \mathrm{best}_j(j).

Lemma 1 (a later candidate that wins keeps winning). Let i<i′<j≤j′i < i' < j \le j'. If gi′(j)≤gi(j)g_{i'}(j) \le g_i(j), then gi′(j′)≤gi(j′)g_{i'}(j') \le g_i(j').

Proof. If gi(j′)=+∞g_i(j') = +\infty there is nothing to show. Otherwise F(i)F(i) and w(i,j′)w(i, j') are finite. By the closure, w(i,j)w(i, j), w(i′,j)w(i', j) and w(i′,j′)w(i', j') are finite too: each pair (i,j)(i, j), (i′,j)(i', j), (i′,j′)(i', j') has i≤i \le its first index and j′≥j' \ge its second index, so if its value were infinite, w(i,j′)w(i, j') would be infinite. Then gi(j)g_i(j) is finite, so gi′(j)≤gi(j)g_{i'}(j) \le g_i(j) makes F(i′)F(i') finite. All four values of the inequality are finite, and adding F(i)+F(i′)F(i) + F(i') to both sides gives gi(j)+gi′(j′)≤gi(j′)+gi′(j)g_i(j) + g_{i'}(j') \le g_i(j') + g_{i'}(j), that is gi′(j′)−gi(j′)≤gi′(j)−gi(j)≤0g_{i'}(j') - g_i(j') \le g_{i'}(j) - g_i(j) \le 0. □\square

Lemma 2 (the new candidate wins on a final interval). Fix j<nj < n and let D={ j′:j<j′≤n, gj(j′)≤bestj(j′) }D = \{\, j' : j < j' \le n,\ g_j(j') \le \mathrm{best}_j(j') \,\}, the targets where the new candidate jj is at least as good as all earlier ones. If j′∈Dj' \in D and j′≤j′′≤nj' \le j'' \le n, then j′′∈Dj'' \in D. So DD is empty or D={d,…,n}D = \{d, \ldots, n\} for some dd.

Proof. Take any c<jc < j. Then gj(j′)≤bestj(j′)≤gc(j′)g_j(j') \le \mathrm{best}_j(j') \le g_c(j'), and Lemma 1 with i=ci = c and i′=ji' = j gives gj(j′′)≤gc(j′′)g_j(j'') \le g_c(j''). This holds for every c<jc < j, so gj(j′′)≤bestj(j′′)g_j(j'') \le \mathrm{best}_j(j''). □\square

Invariant. At the start of step jj (line L3), the queue holds pairs (c1,s1),…,(cr,sr)(c_1, s_1), \ldots, (c_r, s_r) with r≥1r \ge 1, c1<⋯<cr<jc_1 < \cdots < c_r < j, s1≤js_1 \le j and s1<s2<⋯<sr≤ns_1 < s_2 < \cdots < s_r \le n, and

(Q) for every j′j' with j≤j′≤nj \le j' \le n, the candidate ctc_t with t=max⁡{ t:st≤j′ }t = \max\{\, t : s_t \le j' \,\} has gct(j′)=bestj(j′)g_{c_t}(j') = \mathrm{best}_j(j').

We say that ctc_t owns the targets j′j' with st≤j′<st+1s_t \le j' < s_{t+1} (with sr+1=n+1s_{r+1} = n + 1).

Initialization. For j=1j = 1 the queue is (0,1)(0, 1) (line L2), and the only candidate is 0.

Maintenance, the value. Line L4 drops the front while s2≤js_2 \le j. A dropped c1c_1 owns no target j′≥jj' \ge j, because s2≤j≤j′s_2 \le j \le j', so (Q) still holds, and now s1≤j<s2s_1 \le j < s_2. Hence c1c_1 owns jj and line L5 sets F[j]=gc1(j)=bestj(j)=F(j)F[j] = g_{c_1}(j) = \mathrm{best}_j(j) = F(j), with P[j]=c1P[j] = c_1 a minimizer.

Maintenance, the new candidate. If j=nj = n the loop ends. Otherwise the step must make (Q) hold for j+1j + 1, where the candidates are 0,…,j0, \ldots, j and bestj+1(j′)=min⁡(bestj(j′),gj(j′))\mathrm{best}_{j+1}(j') = \min(\mathrm{best}_j(j'), g_j(j')). By Lemma 2, jj attains this minimum exactly on DD, a final interval {d,…,n}\{d, \ldots, n\} 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 dd, followed by (j,d)(j, d).

Lines L6 to L9 build this queue. Look at the back pair (cr,sr)(c_r, s_r) and let s=max⁡(sr,j+1)s = \max(s_r, j + 1); the back candidate owns all of s,…,ns, \ldots, n. Line L7 compares gj(s)g_j(s) with gcr(s)=bestj(s)g_{c_r}(s) = \mathrm{best}_j(s).

  • If gj(s)≤gcr(s)g_j(s) \le g_{c_r}(s), then s∈Ds \in D, so by Lemma 2 all targets from ss to nn are in DD, and crc_r is no longer needed for any target ≥j+1\ge j + 1: every target it owns is at least ss, or below j+1j + 1. Line L7 drops it. The new back pair now owns up to nn, and on the targets it did not own before, jj wins anyway, so the argument repeats with the new back pair.
  • Otherwise s∉Ds \notin D, so D⊆{s+1,…,n}D \subseteq \{s + 1, \ldots, n\}. On s,…,ns, \ldots, n the back candidate owns every target, so for s<c≤ns < c \le n the test gj(c)≤gcr(c)g_j(c) \le g_{c_r}(c) is the test c∈Dc \in D, which is false and then true by Lemma 2. The binary search of line L8 keeps the invariant that every c<loc < lo in its range is not in DD and every c≥hic \ge hi in the range s+1,…,ns + 1, \ldots, n is in DD, or hi=n+1hi = n + 1; it stops with lo=dlo = d, the least element of DD, or lo=n+1lo = n + 1 when DD is empty. Line L9 appends (j,d)(j, d) when d≤nd \le n.
  • If every pair is dropped, then D⊇{j+1,…,n}D \supseteq \{j + 1, \ldots, n\}: the last dropped pair was the front, with s=max⁡(s1,j+1)=j+1s = \max(s_1, j+1) = j + 1. Line L10 appends (j,j+1)(j, j + 1).

In all cases the new queue is the right one. The order conditions hold: cr<jc_r < j, and the new start dd is larger than the ss of the last kept pair, since d≥s+1>srd \ge s + 1 > s_r. The front start is at most j+1j + 1: either the front is unchanged with s1≤js_1 \le j, or it is (j,j+1)(j, j + 1). So the invariant holds at the start of step j+1j + 1.

Termination. The outer loop runs nn 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 2n2n drops in all, and each binary search makes at most ⌈log⁡2n⌉+1\lceil \log_2 n \rceil + 1 steps.

Conclusion. By the maintenance step, F[j]=F(j)F[j] = F(j) and P[j]P[j] is a minimizer for every j=1,…,nj = 1, \ldots, n, and F[0]=0F[0] = 0 by line L1. Each step evaluates ww once in line L5, twice for each dropped pair, and twice per step of the binary search, so the total is O(nlog⁡n)O(n \log n). ■\blacksquare

Why the closure is needed. If an infinite value sits inside a finite region, Lemma 1 can fail. Take w(i′,j′)=+∞w(i', j') = +\infty for one pair and finite values around it: the later candidate i′i' can win at j<j′j < j' and lose at j′j' 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 2n2n pairs in all. Each step evaluates ww 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 nn targets. So the number of evaluations is at most about 2nlog⁡2n+5n2 n \log_2 n + 5 n, and the time is O(nlog⁡n)O(n \log n). The space is Θ(n)\Theta(n) for FF, PP and the queue.

Measured with the kind of weights that the tests of this page use, random concave weights of the form f(Sj−Si−l)+a(i)+b(j)f(S_j - S_i - l) + a(i) + b(j) for a convex ff, the program makes about 19.4n19.4 n evaluations for n=500n = 500, 23.5n23.5 n for n=2000n = 2000, 27.4n27.4 n for n=8000n = 8000 and 31.3n31.3 n for n=32000n = 32000: the count per index grows by about 4 each time nn grows by a factor of 4, as 2log⁡2n2 \log_2 n predicts. On w(i,j)=(j−i−3)2w(i, j) = (j - i - 3)^2 with n=1000n = 1000 it makes 21588 evaluations, while the dynamic program makes n(n+1)/2=500500n(n+1)/2 = 500500.

Properties

  • Values in order. It finds F(1),F(2),…F(1), F(2), \ldots in this order, and F(j)F(j) is final at step jj.
  • Not online in the weights. At step jj it reads w(j,t)w(j, t) for targets tt up to nn, 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 FF and ww, so with exact numbers, such as integers or fractions, the values are exact.
  • Ties. The test ≤\le at lines L7 and L8 lets a later candidate win a tie. The value F(j)F(j) 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 O(n)O(n) time. Galil and Park gave a simpler O(n)O(n) method in 1990.
  • The reverse inequality. If ww satisfies the inequality with ≥\ge, 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 gi(j)g_i(j) is a linear function of a value of jj for each fixed ii, 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 O(nlog⁡n)O(n \log n) per layer, or by SMAWK in O(n)O(n).
  • Free last line. When the last line of a paragraph costs nothing, the weight to nn breaks the inequality. Run the algorithm up to n−1n - 1 with the concave weight, then take F(n)=min⁡i(F(i)+w(i,n))F(n) = \min_i \bigl( F(i) + w(i, n) \bigr) in one more pass.

When to use it

Use it for a dynamic program of the form F(j)=min⁡i<jF(i)+w(i,j)F(j) = \min_{i < j} F(i) + w(i, j) 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 log⁡n\log n factor is small in practice. For the strict O(n)O(n) 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_fail shows 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 max⁡(s,j+1)\max(s, j + 1), because targets at or before jj are already done. The program also must not append a pair whose start is beyond nn.

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.

hirschberg_larmore_algorithm.pyI0RawGitHub
# 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 O(nlog⁡n)O(n \log n) algorithm, with the breaking of paragraphs into lines as the main application. Wilber reduced the time to O(n)O(n) 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example