Algorithm Search⌘K

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))
Properties
deterministicofflinerecursive
Origin
Robert Wilber, 1988

Wilber's 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(n)O(n) time when the weight ww satisfies the quadrangle inequality, the case that Hirschberg and Larmore call concave. The array B(j,i)=F(i)+w(i,j)B(j, i) = F(i) + w(i, j) is then totally monotone, so SMAWK could find all its row minima in O(n)O(n) time, if the array were known. But the column ii needs F(i)F(i), 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 O(nlog⁡n)O(n \log n) 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 ii are known only after the answer for ii.

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 n≥1n \ge 1 and a finite 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, with

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 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. The weights must be finite; a line that is too long gets a large finite penalty instead of +∞+\infty (see Pitfalls).

The algorithm

The array GG holds the final values F(i)F(i) for i≤ci \le c and guesses after cc. A call of SMAWK on targets JJ and candidates II finds, for each j∈Jj \in J, the leftmost i∈Ii \in I that minimizes B(j,i)=G[i]+w(i,j)B(j, i) = G[i] + w(i, j), with B(j,i)=+∞B(j, i) = +\infty when i≥ji \ge j. The state is a pair (c,r)(c, r): F(0),…,F(c)F(0), \ldots, F(c) are final, and for every target after cc, the candidates before rr can be ignored.

  1. WILBER(n, w)
  2. W1 F[0] ← G[0] ← 0; c ← 0; r ← 0
  3. W2 while c < n do
  4. W3 p ← min(2c - r + 1, n)
  5. W4 SMAWK on the targets c + 1 .. p and the candidates r .. c
  6. W5 for j ← c + 1 to p do G[j] ← the minimum for j; P[j] ← its candidate
  7. W6 if p ≥ c + 2 then SMAWK on the targets c + 2 .. p and the candidates c + 1 .. p - 1; H(j) ← the minimum for j
  8. W7 j0 ← the least target j with H(j) < G[j], or none
  9. W8 if there is no j0 then
  10. W9 F[c + 1 .. p] ← G[c + 1 .. p]; c ← p
  11. else
  12. W10 F[c + 1 .. j0 - 1] ← G[c + 1 .. j0 - 1]; F[j0] ← G[j0] ← H(j0); P[j0] ← its candidate
  13. W11 r ← c + 1; c ← j0
  14. W12 return F, P

Line W3 picks a block of at most c−r+1c - r + 1 targets, the number of live candidates, so that the cost of the block is paid by the growth of cc or of rr. Lines W4 and W5 compute the guess G[j]=min⁡i≤cgi(j)G[j] = \min_{i \le c} g_i(j) for the block, where gi(j)=F(i)+w(i,j)g_i(j) = F(i) + w(i, j); all its candidates are final. Line W6 computes H(j)=min⁡c<i<j(G[i]+w(i,j))H(j) = \min_{c < i < j} \bigl( G[i] + w(i, j) \bigr), 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 n=10n = 10 and w(i,j)=(j−i−2)2w(i, j) = (j - i - 2)^2, a weight that wants every jump to have length 2. The optimum is F(j)=0F(j) = 0 for even jj and F(j)=1F(j) = 1 for odd jj.

pass cc, rr pp guesses of lines W4 and W5 (candidate) check of lines W6 and W7 result
1 0, 0 1 G[1]=1G[1] = 1 (0) none, the block has one target c=1c = 1
2 1, 0 3 G[2]=0G[2] = 0 (0), G[3]=1G[3] = 1 (0) H(3)=1H(3) = 1, not less c=3c = 3
3 3, 0 7 G[4]=0G[4] = 0 (2), G[5]=1G[5] = 1 (2), G[6]=2G[6] = 2 (3), G[7]=5G[7] = 5 (3) H(5)=1H(5) = 1, H(6)=0<2H(6) = 0 < 2 failure at 6: F(6)=0F(6) = 0 from 4; r=4r = 4, c=6c = 6
4 6, 4 9 G[7]=1G[7] = 1 (4), G[8]=0G[8] = 0 (6), G[9]=1G[9] = 1 (6) H(8)=2H(8) = 2, H(9)=1H(9) = 1, not less c=9c = 9
5 9, 4 10 G[10]=0G[10] = 0 (8) none c=10c = 10

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 F(4)F(4) and F(5)F(5), sets F(6)F(6) 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 10→8→6→4→2→010 \to 8 \to 6 \to 4 \to 2 \to 0, with weight 0.

On the check value w(i,j)=(j−i−3)2w(i, j) = (j - i - 3)^2 of the least weight subsequence page, the check never fails, and the passes have c=0,1,3,7c = 0, 1, 3, 7 and end at 10.

Correctness

Two facts carry the proof. First, for candidates i<i′i < i' and targets j<j′j < j', with all entries finite, the inequality gives B(j′,i)−B(j′,i′)≥B(j,i)−B(j,i′)B(j', i) - B(j', i') \ge B(j, i) - B(j, i'), for any values in GG, since only G[i]+G[i′]G[i] + G[i'] is added to both sides. So the arrays of lines W4 and W6 are totally monotone, and SMAWK returns their leftmost row minima with O(∣I∣+∣J∣)O(|I| + |J|) evaluations. The entries +∞+\infty for i≥ji \ge j lie in a staircase that keeps this property.

Second, the invariant: at line W2, F[i]=F(i)F[i] = F(i) for i≤ci \le c, and for every target after cc, the best candidate among 0,…,c0, \ldots, c is also found among r,…,cr, \ldots, c. Then G[j]G[j] from line W5 is the best value over the final candidates. By induction over the block, every guess before j0j_0 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 H(j)≥G[j]H(j) \ge G[j] means that none of them is better. At j0j_0, the same argument shows F(j0)=H(j0)F(j_0) = H(j_0). A candidate i∗i^* in the block that beats every i≤ci \le c at j0j_0 beats them at every later target, by the first fact, which allows r←c+1r \leftarrow c + 1. The full proof is in the proof file.

Proof: Wilber's guess and check gives the least weight subsequence in linear timefull

Claim. Let n≥1n \ge 1 and let w(i,j)w(i, j), for 0≤i<j≤n0 \le i < j \le n, be finite reals with

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',

the condition that Hirschberg and Larmore call concave (the quadrangle inequality of a Monge array). Then WILBER (lines W1 to W12) 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)), with F[P[j]]+w(P[j],j)=F(j)F[P[j]] + w(P[j], j) = F(j). It uses O(n)O(n) evaluations of ww.

Setup. Write gi(j)=F(i)+w(i,j)g_i(j) = F(i) + w(i, j) for i<ji < j. The program keeps an array GG of values: final values F(i)F(i) for i≤ci \le c and guesses after cc. For a set of targets JJ and a set of candidates II, the call of SMAWK in lines W4 and W6 works on the array MM with a row for each j∈Jj \in J and a column for each i∈Ii \in I, both in increasing order, with M[j][i]=G[i]+w(i,j)M[j][i] = G[i] + w(i, j) if i<ji < j and +∞+\infty if i≥ji \ge j, and returns for each row the leftmost column of its minimum.

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) < g_i(j), then gi′(j′)≤gi(j′)g_{i'}(j') \le g_i(j'). The same holds with any values GG in place of FF.

Proof. The inequality with F(i)+F(i′)F(i) + F(i') added to both sides gives gi′(j′)−gi(j′)≤gi′(j)−gi(j)<0g_{i'}(j') - g_i(j') \le g_{i'}(j) - g_i(j) < 0. Only the sum of a value of ii and a value of i′i' is added, so any values work. □\square

Lemma 2 (the arrays are totally monotone). For rows j<j′j < j' and columns i<i′i < i' of MM, if M[j][i]>M[j][i′]M[j][i] > M[j][i'] then M[j′][i]>M[j′][i′]M[j'][i] > M[j'][i']. So SMAWK returns the leftmost minimum of each row with O(∣I∣+∣J∣)O(|I| + |J|) evaluations (see SMAWK).

Proof. From M[j][i]>M[j][i′]M[j][i] > M[j][i'], the entry M[j][i′]M[j][i'] is finite, so i<i′<j<j′i < i' < j < j' and all four entries are finite. Then Lemma 1 with GG gives M[j′][i]−M[j′][i′]≥M[j][i]−M[j][i′]>0M[j'][i] - M[j'][i'] \ge M[j][i] - M[j][i'] > 0. (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 ∣J∣|J| columns with O(∣I∣)O(|I|) evaluations, the recursion is on half of the rows, and the interpolation reads each kept column O(1)O(1) times per row, so T(∣J∣,∣I∣)=O(∣I∣)+T(∣J∣/2,∣J∣)+O(∣J∣)=O(∣I∣+∣J∣)T(|J|, |I|) = O(|I|) + T(|J|/2, |J|) + O(|J|) = O(|I| + |J|). □\square

Invariant. At the start of each pass of the loop of line W2:

  • (W1) 0≤r≤c≤n0 \le r \le c \le n, and F[i]=G[i]=F(i)F[i] = G[i] = F(i) for 0≤i≤c0 \le i \le c;
  • (W2) for every target jj with c<j≤nc < j \le n, min⁡0≤i≤cgi(j)=min⁡r≤i≤cgi(j)\min_{0 \le i \le c} g_i(j) = \min_{r \le i \le c} g_i(j): the candidates before rr can be ignored.

Initialization. Line W1 sets c=r=0c = r = 0 and F[0]=G[0]=0=F(0)F[0] = G[0] = 0 = F(0). (W2) holds because both sides are g0(j)g_0(j).

Maintenance. Let p=min⁡(2c−r+1,n)p = \min(2c - r + 1, n) (line W3). Since r≤cr \le c, p≥c+1p \ge c + 1, and p−c≤c−r+1p - c \le c - r + 1.

The guesses. Line W4 runs SMAWK on the targets c+1,…,pc + 1, \ldots, p and the candidates r,…,cr, \ldots, c. All candidates are below all targets, so all entries are finite and use final values. By Lemma 2 and (W2), line W5 sets G[j]=N(j):=min⁡i≤cgi(j)G[j] = N(j) := \min_{i \le c} g_i(j) for c<j≤pc < j \le p. For each such jj,

F(j)=min⁡(N(j), min⁡c<i<jgi(j)).(1)F(j) = \min\bigl(N(j),\ \min_{c < i < j} g_i(j)\bigr). \tag{1}

The check. If p≥c+2p \ge c + 2, line W6 runs SMAWK on the targets c+2,…,pc + 2, \ldots, p and the candidates c+1,…,p−1c + 1, \ldots, p - 1 with the guesses GG. For a target jj the finite entries are the candidates c+1,…,j−1c + 1, \ldots, j - 1, so it returns H(j)=min⁡c<i<j(G[i]+w(i,j))H(j) = \min_{c < i < j} (G[i] + w(i, j)) and a column where it is attained. Let j0j_0 be the least target with H(j0)<G[j0]H(j_0) < G[j_0] (line W7), or j0=p+1j_0 = p + 1 if there is none (and also if p=c+1p = c + 1).

Claim A: F(j)=G[j]F(j) = G[j] for c<j<j0c < j < j_0. By induction on jj. For j=c+1j = c + 1, the inner minimum of (1) is empty, so F(c+1)=N(c+1)F(c+1) = N(c+1). For c+2≤j<j0c + 2 \le j < j_0, the hypothesis gives F(i)=G[i]F(i) = G[i] for c<i<jc < i < j, so the inner minimum of (1) is H(j)H(j), and H(j)≥G[j]=N(j)H(j) \ge G[j] = N(j) because j<j0j < j_0. So F(j)=N(j)=G[j]F(j) = N(j) = G[j].

Claim B: if j0≤pj_0 \le p, then F(j0)=H(j0)F(j_0) = H(j_0). By Claim A all the values that H(j0)H(j_0) uses are final, so H(j0)=min⁡c<i<j0gi(j0)H(j_0) = \min_{c < i < j_0} g_i(j_0), and by (1) F(j0)=min⁡(N(j0),H(j0))=H(j0)F(j_0) = \min(N(j_0), H(j_0)) = H(j_0), since H(j0)<N(j0)H(j_0) < N(j_0).

No failure (lines W8 and W9). Then j0=p+1j_0 = p + 1. By Claim A, setting F[j]=G[j]F[j] = G[j] for c<j≤pc < j \le p and c←pc \leftarrow p keeps (W1). (W2) for the new c=pc = p and the same rr: for j>pj > p, the candidates i≤ci \le c (old cc) reduce to r,…,cr, \ldots, c by the old (W2), and the candidates c<i≤pc < i \le p are all at least rr. So (W2) holds.

Failure (lines W10 and W11). By Claims A and B, the values set for c<j≤j0c < j \le j_0 are final, and G[j0]G[j_0] is set to F(j0)F(j_0), so (W1) holds for the new c=j0c = j_0; also the new r=c+1≤j0r = c + 1 \le j_0. For (W2), let i∗i^* be the column that line W6 returned for j0j_0, so c<i∗<j0c < i^* < j_0 and gi∗(j0)=H(j0)<N(j0)≤gi(j0)g_{i^*}(j_0) = H(j_0) < N(j_0) \le g_i(j_0) for every i≤ci \le c. By Lemma 1, gi∗(j)≤gi(j)g_{i^*}(j) \le g_i(j) for every j>j0j > j_0 and every i≤ci \le c. So for j>j0j > j_0 the candidates 0,…,c0, \ldots, c are never better than i∗i^*, which lies in c+1,…,j0c + 1, \ldots, j_0, and (W2) holds with r=c+1r = c + 1.

Termination. Each pass increases cc: to p≥c+1p \ge c + 1, or to j0≥c+2j_0 \ge c + 2. So the loop stops with c=nc = n, and by (W1) F[j]=F(j)F[j] = F(j) for all jj. The predecessor P[j]P[j] is the column where the minimum was attained, so F[P[j]]+w(P[j],j)=F(j)F[P[j]] + w(P[j], j) = F(j).

Cost. By Lemma 2, a pass costs O((c−r+1)+(p−c))=O(c−r+1)O((c - r + 1) + (p - c)) = O(c - r + 1) evaluations, since p−c≤c−r+1p - c \le c - r + 1. In a pass without failure and with p=2c−r+1p = 2c - r + 1, cc grows by c−r+1c - r + 1. In a pass with failure, rr grows from rr to c+1c + 1, that is by c−r+1c - r + 1. At most one pass has p=n<2c−r+1p = n < 2c - r + 1 and no failure, the last one, and it costs O(n)O(n). Both cc and rr never decrease and stay at most nn, and there are at most nn passes, so the total is O(n+n+n)=O(n)O(n + n + n) = O(n) evaluations. ■\blacksquare

Why the weights must be finite. If w(i,j)=+∞w(i, j) = +\infty marks a line that is too long, then an infinite entry M[j][i]M[j][i] with a finite M[j][i′]M[j][i'] 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 O((c−r+1)+(p−c))O((c - r + 1) + (p - c)) evaluations, which is O(c−r+1)O(c - r + 1) because line W3 makes p−c≤c−r+1p - c \le c - r + 1. A pass with no failure and p=2c−r+1p = 2c - r + 1 increases cc by c−r+1c - r + 1. A pass with a failure increases rr from rr to c+1c + 1, also by c−r+1c - r + 1. The last pass may have p=np = n and cost O(n)O(n). Since cc and rr never decrease and stay at most nn, the total is O(n)O(n) evaluations and O(n)O(n) time. The space is Θ(n)\Theta(n) for FF, GG, PP and the lists of SMAWK.

Measured with the kind of weights that the tests of this page use, random weights 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 17.1n17.1 n evaluations for n=500n = 500, 16.5n16.5 n for n=2000n = 2000, 14.8n14.8 n for n=8000n = 8000 and 14.9n14.9 n for n=32000n = 32000: the count per index does not grow. On w(i,j)=(j−i−3)2w(i, j) = (j - i - 3)^2 it makes 12968 evaluations for n=1000n = 1000 and 103962 for n=8000n = 8000, against 21588 and 220912 for the Hirschberg-Larmore algorithm and 500500 for the dynamic program at n=1000n = 1000.

Properties

  • Optimal. The time O(n)O(n) is the best possible, since the output has nn values.
  • Not online. It guesses values ahead and reads weights w(i,j)w(i, j) for targets in the whole block, so all weights must be known in advance.
  • Guesses are thrown away. After a failure, the guesses after j0j_0 are computed again in the next pass. The analysis charges this work to the growth of rr.
  • 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 O(n)O(n) algorithm for the same concave problem in 1990.
  • The O(nlog⁡n)O(n \log n) 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 nn 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 log⁡n\log n 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 w(i,j)=+∞w(i, j) = +\infty 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_fail finds such inputs. Use a large finite penalty that is a convex function of the width, such as Kmax⁡(0,Sj−Si−lmax⁡)K \max(0, S_j - S_i - l_{\max}) for a large KK; 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 FF 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 rr pays for.
  • The strict check. Line W7 must test H(j)<G[j]H(j) < G[j]. 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.

wilber_algorithm.pyI0RawGitHub
# 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 O(nlog⁡n)O(n \log n) time. Wilber showed in 1988 how to use SMAWK when the matrix is not given in advance, and so solved the concave case in O(n)O(n) time. Galil and Park gave a simpler linear algorithm in 1990.

References

  1. Robert Wilber, The concave least-weight subsequence problem revisited, Journal of Algorithms 9(3), 418-425, 1988, the O(n) algorithm for concave weights
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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