Algorithmresearch
Wilber's algorithm
Also called linear-time least weight subsequence.
Solve the concave least weight subsequence problem in O(n) time by applying SMAWK to blocks of the online dynamic program.
- Time
- O(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
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Robert Wilber, 1988
Wilber's algorithm solves the least weight subsequence problem , in time when the weight satisfies the quadrangle inequality, the case that Hirschberg and Larmore call concave. The array is then totally monotone, so SMAWK could find all its row minima in time, if the array were known. But the column needs , which is itself a row minimum. Wilber's method works on blocks: it guesses the values of a block of targets from the candidates that are already final, uses the guesses to check themselves with a second SMAWK call, and restarts after the first target where the check fails. The block sizes are chosen so that the total work is linear. Robert Wilber, one of the authors of SMAWK, published it in 1988, improving the bound of the Hirschberg-Larmore algorithm.
In plain words
The fast way to find the minimum of every row of a totally monotone table is SMAWK, but it needs the whole table at the start. Here the table fills in as the answers come: the entries of column are known only after the answer for .
So the method guesses. It computes, for the next block of targets, the best value using only the candidates that are already final. These guesses may be too high, because the candidates inside the block were left out.
It then asks a second question with SMAWK: could a candidate inside the block, using the guessed values, beat a guess? If not, all the guesses are right. If yes, the first guess that is beaten is fixed, the guesses before it are right, and the method starts a new block after it.
The problem
The input is an integer and a finite weight for , given by a procedure that returns any weight in time, with
The output is and, for each , an index that attains the minimum. The weights must be finite; a line that is too long gets a large finite penalty instead of (see Pitfalls).
The algorithm
The array holds the final values for and guesses after . A call of SMAWK on targets and candidates finds, for each , the leftmost that minimizes , with when . The state is a pair : are final, and for every target after , the candidates before can be ignored.
WILBER(n, w)W1 F[0] ← G[0] ← 0; c ← 0; r ← 0W2 while c < n doW3 p ← min(2c - r + 1, n)W4 SMAWK on the targets c + 1 .. p and the candidates r .. cW5 for j ← c + 1 to p do G[j] ← the minimum for j; P[j] ← its candidateW6 if p ≥ c + 2 then SMAWK on the targets c + 2 .. p and the candidates c + 1 .. p - 1; H(j) ← the minimum for jW7 j0 ← the least target j with H(j) < G[j], or noneW8 if there is no j0 thenW9 F[c + 1 .. p] ← G[c + 1 .. p]; c ← pelseW10 F[c + 1 .. j0 - 1] ← G[c + 1 .. j0 - 1]; F[j0] ← G[j0] ← H(j0); P[j0] ← its candidateW11 r ← c + 1; c ← j0W12 return F, P
Line W3 picks a block of at most targets, the number of live candidates, so that the cost of the block is paid by the growth of or of . Lines W4 and W5 compute the guess for the block, where ; all its candidates are final. Line W6 computes , the best value from a candidate inside the block, using the guesses as if they were final. Line W7 looks for the first target where a candidate inside the block beats the guess.
Example
Take and , a weight that wants every jump to have length 2. The optimum is for even and for odd .
| pass | , | guesses of lines W4 and W5 (candidate) | check of lines W6 and W7 | result | |
|---|---|---|---|---|---|
| 1 | 0, 0 | 1 | (0) | none, the block has one target | |
| 2 | 1, 0 | 3 | (0), (0) | , not less | |
| 3 | 3, 0 | 7 | (2), (2), (3), (3) | , | failure at 6: from 4; , |
| 4 | 6, 4 | 9 | (4), (6), (6) | , , not less | |
| 5 | 9, 4 | 10 | (8) | none |
In pass 3 the guesses for 6 and 7 are too high, because the best last break for them is 4, a candidate inside the block. The check finds this at 6, keeps and , sets from candidate 4, and drops the candidates 0 to 3 for all later targets, since candidate 4 beats all of them at 6. The guess for 7 is thrown away and computed again in pass 4. The back pointers give , with weight 0.
On the check value of the least weight subsequence page, the check never fails, and the passes have and end at 10.
Correctness
Two facts carry the proof. First, for candidates and targets , with all entries finite, the inequality gives , for any values in , since only is added to both sides. So the arrays of lines W4 and W6 are totally monotone, and SMAWK returns their leftmost row minima with evaluations. The entries for lie in a staircase that keeps this property.
Second, the invariant: at line W2, for , and for every target after , the best candidate among is also found among . Then from line W5 is the best value over the final candidates. By induction over the block, every guess before is right: the first target has no candidate inside the block, and for a later one the candidates inside the block have right values, so means that none of them is better. At , the same argument shows . A candidate in the block that beats every at beats them at every later target, by the first fact, which allows . The full proof is in the proof file.
Proof: Wilber's guess and check gives the least weight subsequence in linear timefull
Claim. Let and let , for , be finite reals with
the condition that Hirschberg and Larmore call concave (the quadrangle inequality of a Monge array). Then WILBER (lines W1 to W12) stops and returns for , where and , with . It uses evaluations of .
Setup. Write for . The program keeps an array of values: final values for and guesses after . For a set of targets and a set of candidates , the call of SMAWK in lines W4 and W6 works on the array with a row for each and a column for each , both in increasing order, with if and if , and returns for each row the leftmost column of its minimum.
Lemma 1 (a later candidate that wins keeps winning). Let . If , then . The same holds with any values in place of .
Proof. The inequality with added to both sides gives . Only the sum of a value of and a value of is added, so any values work.
Lemma 2 (the arrays are totally monotone). For rows and columns of , if then . So SMAWK returns the leftmost minimum of each row with evaluations (see SMAWK).
Proof. From , the entry is finite, so and all four entries are finite. Then Lemma 1 with gives . (The infinite entries lie where the column is at least the row, so a row's finite entries form a prefix that grows with the row; this pattern keeps the strict condition.) The cost bound is the one of SMAWK: REDUCE keeps at most columns with evaluations, the recursion is on half of the rows, and the interpolation reads each kept column times per row, so .
Invariant. At the start of each pass of the loop of line W2:
- (W1) , and for ;
- (W2) for every target with , : the candidates before can be ignored.
Initialization. Line W1 sets and . (W2) holds because both sides are .
Maintenance. Let (line W3). Since , , and .
The guesses. Line W4 runs SMAWK on the targets and the candidates . All candidates are below all targets, so all entries are finite and use final values. By Lemma 2 and (W2), line W5 sets for . For each such ,
The check. If , line W6 runs SMAWK on the targets and the candidates with the guesses . For a target the finite entries are the candidates , so it returns and a column where it is attained. Let be the least target with (line W7), or if there is none (and also if ).
Claim A: for . By induction on . For , the inner minimum of (1) is empty, so . For , the hypothesis gives for , so the inner minimum of (1) is , and because . So .
Claim B: if , then . By Claim A all the values that uses are final, so , and by (1) , since .
No failure (lines W8 and W9). Then . By Claim A, setting for and keeps (W1). (W2) for the new and the same : for , the candidates (old ) reduce to by the old (W2), and the candidates are all at least . So (W2) holds.
Failure (lines W10 and W11). By Claims A and B, the values set for are final, and is set to , so (W1) holds for the new ; also the new . For (W2), let be the column that line W6 returned for , so and for every . By Lemma 1, for every and every . So for the candidates are never better than , which lies in , and (W2) holds with .
Termination. Each pass increases : to , or to . So the loop stops with , and by (W1) for all . The predecessor is the column where the minimum was attained, so .
Cost. By Lemma 2, a pass costs evaluations, since . In a pass without failure and with , grows by . In a pass with failure, grows from to , that is by . At most one pass has and no failure, the last one, and it costs . Both and never decrease and stay at most , and there are at most passes, so the total is evaluations.
Why the weights must be finite. If marks a line that is too long, then an infinite entry with a finite forces nothing on a later row where both entries are infinite, so the strict condition of Lemma 2 fails, and SMAWK can drop the column that holds the minimum. The test test_infinite_weights_can_fail finds such inputs. A large finite penalty that is a convex function of the width keeps the inequality and avoids the problem.
Complexity
By the bound of SMAWK, a pass costs evaluations, which is because line W3 makes . A pass with no failure and increases by . A pass with a failure increases from to , also by . The last pass may have and cost . Since and never decrease and stay at most , the total is evaluations and time. The space is for , , and the lists of SMAWK.
Measured with the kind of weights that the tests of this page use, random weights for a convex , the program makes about evaluations for , for , for and for : the count per index does not grow. On it makes 12968 evaluations for and 103962 for , against 21588 and 220912 for the Hirschberg-Larmore algorithm and 500500 for the dynamic program at .
Properties
- Optimal. The time is the best possible, since the output has values.
- Not online. It guesses values ahead and reads weights for targets in the whole block, so all weights must be known in advance.
- Guesses are thrown away. After a failure, the guesses after are computed again in the next pass. The analysis charges this work to the growth of .
- Exact. It uses only comparisons and additions, so with integers or fractions the values are exact.
Variants and improvements
- Simpler linear methods. Galil and Park gave a simpler algorithm for the same concave problem in 1990.
- The queue method. The Hirschberg-Larmore algorithm is much shorter and is often fast enough. On the weights above it makes about 1.4 to 2.1 times as many evaluations for from 1000 to 8000.
- The reverse inequality. For weights with the inequality reversed, the arrays are not totally monotone in the needed direction. The best known methods take almost linear time, see the least weight subsequence page.
- Layers. For a fixed number of parts, each layer of the dynamic program depends only on the layer before, so its matrix is known in advance and plain SMAWK (row minima of totally monotone matrices) applies with no guessing.
When to use it
Use it when the strict linear bound matters, for very long sequences with a concave weight, such as line breaking with rigid spaces and a convex cost of the slack (printing neatly, optimal text wrapping). For paragraphs of normal size, the factor of the Hirschberg-Larmore algorithm costs little, and that method is simpler to get right. Neither applies directly to the demerits of Knuth-Plass line breaking, which depend on more than the two ends of a line.
Pitfalls
- Infinite weights. With for a line that is too long, two infinite entries compare equal, the strict condition of total monotonicity fails, and SMAWK can drop the column that holds the minimum. The test
test_infinite_weights_can_failfinds such inputs. Use a large finite penalty that is a convex function of the width, such as for a large ; it keeps the inequality. - Running SMAWK on the whole array. The array is not known in advance, so a single call over all rows and columns reads values of that are not computed yet.
- The block size. A block larger than the number of live candidates breaks the bound, because a failure early in the block then wastes more work than the growth of pays for.
- The strict check. Line W7 must test . A tie means the guess is already right.
- The constant. Each pass makes two SMAWK calls and some guesses are computed twice, so the constant factor is larger than that of the simple queue method.
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/wilber-algorithm/. The authors are listed in prov/BV1WAB.jsonl.
"""Wilber's algorithm: the concave least weight subsequence problem in O(n).
F(0) = 0 and F(j) = min over 0 <= i < j of F(i) + w(i, j), for j = 1 .. n,
where w(i, j) + w(i', j') <= w(i, j') + w(i', j) for all i <= i' < j <= j'
(concave in the word of Hirschberg and Larmore, the Monge or quadrangle
inequality). Let B(i, j) = F(i) + w(i, j) for i < j and +infinity for
i >= j. B is a Monge array, so its column minima can be found with SMAWK in
time linear in its size. SMAWK cannot run on all of B at once, because the
row i is known only after the column i is done. Wilber guesses the values of
a block of columns from the rows that are known, uses the guesses to check
them, and moves to the first column where the check fails.
The state is (c, r): F(0) .. F(c) are final, and for every column after c,
some row in r .. c is at least as good as every row before r.
w must be finite. If w(i, j) = math.inf marks a line that is too long, two
infinite entries compare equal and SMAWK can drop the wrong row. Use a large
finite penalty that keeps the inequality instead, for example
K * max(0, S_j - S_i - l_max) with K large: it is a convex function of the
width S_j - S_i, so the weight stays concave.
"""
import math
from typing import Callable, Dict, List, Optional, Sequence, Tuple
Weight = Callable[[int, int], float]
def smawk(rows: Sequence[int], cols: Sequence[int], f: Callable[[int, int], float]) -> Dict[int, int]:
"""Row minima of a totally monotone array: {row: the leftmost column of its minimum}.
The array is given by f(row, col). Its rows and columns are in the order
of the lists. The cost is O(len(rows) + len(cols)) evaluations of f.
"""
result: Dict[int, int] = {}
def solve(rows: Sequence[int], cols: Sequence[int]) -> None:
if not rows:
return
stack: List[int] = [] # REDUCE: keep at most len(rows) columns
for c in cols:
while stack and f(rows[len(stack) - 1], stack[-1]) > f(rows[len(stack) - 1], c):
stack.pop()
if len(stack) < len(rows):
stack.append(c)
solve(rows[1::2], stack)
k = 0
for t in range(0, len(rows), 2): # interpolate the even rows
row = rows[t]
stop = result[rows[t + 1]] if t + 1 < len(rows) else stack[-1]
best, bv = stack[k], f(row, stack[k])
while stack[k] != stop:
k += 1
v = f(row, stack[k])
if v < bv:
best, bv = stack[k], v
result[row] = best
solve(list(rows), list(cols))
return result
def wilber(n: int, w: Weight, stats: Optional[dict] = None) -> Tuple[List, List[int]]:
"""F[0..n] and the best predecessor P[1..n], with O(n) evaluations of w."""
evals = 0
F: List = [0] + [math.inf] * n
P = [0] * (n + 1)
G: List = list(F) # the guesses: F for columns <= c, tentative values after c
def B(j: int, i: int): # the entry of row i and column j, from the guesses
nonlocal evals
if i >= j:
return math.inf
evals += 1
return G[i] + w(i, j)
c, r = 0, 0 # @line W1
while c < n: # @line W2
p = min(2 * c - r + 1, n) # @line W3
# guesses for the columns c+1 .. p from the final rows r .. c
cols = list(range(c + 1, p + 1))
arg = smawk(cols, list(range(r, c + 1)), B) # @line W4
for j in cols:
G[j], P[j] = B(j, arg[j]), arg[j] # @line W5
# check: can a row in c+1 .. p-1, with the guessed values, beat a guess?
j0 = None
if p >= c + 2:
cols2 = list(range(c + 2, p + 1))
arg2 = smawk(cols2, list(range(c + 1, p)), B) # @line W6
for j in cols2:
if B(j, arg2[j]) < G[j]: # @line W7
j0 = j
break
if j0 is None: # @line W8
for j in cols:
F[j] = G[j]
c = p # @line W9
else:
for j in range(c + 1, j0):
F[j] = G[j]
G[j0] = F[j0] = B(j0, arg2[j0]) # @line W10
P[j0] = arg2[j0]
r, c = c + 1, j0 # @line W11
if stats is not None:
stats["evals"] = evals
return F, P # @line W12
test_wilber_algorithm.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wilber-algorithm/. The authors are listed in prov/BV1WAB.jsonl.
import math
import random
from fractions import Fraction
from wilber_algorithm import smawk, wilber
def lws_dp(n, w):
F = [0] + [math.inf] * n
for j in range(1, n + 1):
F[j] = min(F[i] + w(i, j) for i in range(j))
return F
def concave_weight(rng, n, line=None):
"""w(i, j) = f(S_j - S_i - l) + a(i) + b(j) with f convex: the quadrangle inequality holds."""
S = [0]
for _ in range(n):
S.append(S[-1] + rng.randint(1, 6))
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):
if line is not None and S[j] - S[i] > line:
return math.inf
d = S[j] - S[i] - l
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 test_smawk_on_random_monge_arrays():
rng = random.Random(1987)
for _ in range(200):
m, k = rng.randint(1, 15), rng.randint(1, 15)
# a sum of a row term, a column term and a convex function of the difference is Monge
u = sorted(rng.randint(0, 30) for _ in range(m))
v = sorted(rng.randint(0, 30) for _ in range(k))
ra = [rng.randint(0, 50) for _ in range(m)]
cb = [rng.randint(0, 50) for _ in range(k)]
f = lambda r, c: (u[r] - v[c]) ** 2 + ra[r] + cb[c]
got = smawk(list(range(m)), list(range(k)), f)
for r in range(m):
vals = [f(r, c) for c in range(k)]
assert got[r] == vals.index(min(vals)) # the leftmost minimum
def test_check_value():
w = lambda i, j: (j - i - 3) ** 2
F, P = wilber(10, w)
assert F == [0, 4, 1, 0, 1, 1, 0, 1, 1, 0, 1]
j, b = 10, []
while j > 0:
b.append(j)
j = P[j]
b.reverse()
assert sum(w(i, j) for i, j in zip([0] + b, b)) == 1
def test_matches_dynamic_program():
rng = random.Random(1988)
for _ in range(200):
n = rng.randint(1, 70)
w = concave_weight(rng, n)
F, P = wilber(n, w)
assert F == lws_dp(n, w)
for j in range(1, n + 1):
assert F[P[j]] + w(P[j], j) == F[j]
def test_fractions_and_ties():
rng = random.Random(8)
for _ in range(60):
n = rng.randint(1, 40)
c = Fraction(rng.randint(1, 5), rng.randint(1, 5))
w = lambda i, j, c=c: c * (j - i - 2) ** 2
assert wilber(n, w)[0] == lws_dp(n, w)
w2 = lambda i, j, c=c: c * (j - i) * (j - i)
assert wilber(n, w2)[0] == lws_dp(n, w2)
def test_infinite_weights_can_fail():
# math.inf for a line that is too long: inf == inf ties break SMAWK
rng = random.Random(12)
bad = 0
for _ in range(150):
n = rng.randint(1, 60)
w = concave_weight(rng, n, line=rng.randint(6, 30))
if wilber(n, w)[0] != lws_dp(n, w):
bad += 1
assert bad > 0
def test_lines_that_are_too_long_with_a_finite_penalty():
rng = random.Random(12)
K = 10**9
for _ in range(150):
n = rng.randint(1, 60)
line = rng.randint(6, 30)
S = [0]
for _ in range(n):
S.append(S[-1] + rng.randint(1, 6))
l = rng.randint(5, line)
w_inf = lambda i, j: math.inf if S[j] - S[i] > line else (S[j] - S[i] - l) ** 2
w_fin = lambda i, j: (S[j] - S[i] - l) ** 2 + K * max(0, S[j] - S[i] - line)
F = wilber(n, w_fin)[0]
G = lws_dp(n, w_inf)
assert F == lws_dp(n, w_fin)
# every line fits here (word widths are at most 6 <= line), so the penalty is never paid
assert F == G
def test_evaluations_are_linear():
rng = random.Random(4)
ratios = []
for n in (500, 2000, 8000):
w = concave_weight(rng, n)
st = {}
wilber(n, w, st)
ratios.append(st["evals"] / n)
assert st["evals"] <= 20 * n
w = lambda i, j: (j - i - 3) ** 2
st = {}
wilber(8000, w, st)
assert st["evals"] <= 20 * 8000
History
Aggarwal, Klawe, Moran, Shor and Wilber published the SMAWK algorithm in 1987, for the row minima of a totally monotone matrix given in advance. In the same year Hirschberg and Larmore defined the least weight subsequence problem and solved the concave case in time. Wilber showed in 1988 how to use SMAWK when the matrix is not given in advance, and so solved the concave case in time. Galil and Park gave a simpler linear algorithm in 1990.
References
- Robert Wilber, The concave least-weight subsequence problem revisited, Journal of Algorithms 9(3), 418-425, 1988, the O(n) algorithm for concave weights
- Alok Aggarwal, Maria M. Klawe, Shlomo Moran, Peter Shor and Robert Wilber, Geometric applications of a matrix-searching algorithm, Algorithmica 2, 195-208, 1987, the SMAWK algorithm for the row minima of a totally monotone matrix
- D. S. Hirschberg and L. L. Larmore, The least weight subsequence problem, SIAM Journal on Computing 16(4), 628-638, 1987, the problem, the concave condition and the O(n log n) algorithm that Wilber improves
- 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
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 BV1WAB Edit this page History Report an error Markdown