Algorithm Search⌘K

Algorithmcore

Tichy's block move algorithm

Also called string-to-string correction with block moves.

Build the target from the fewest copied blocks of the source and added symbols, by taking the longest block of the source that matches at each position.

Time
O(m n) worst
Space
O(1) extra
Where
m = the length of the source S; n = the length of the target T
Properties
deterministicgreedyonlineiterative

Tichy's block move algorithm writes a target string TT as a list of moves: a copy of a block of the source string SS, or an add of one symbol that does not occur in SS. At each position of TT it takes the longest block of SS that matches there. Walter Tichy proved in 1984 that this greedy rule gives the fewest moves. A block of SS may be copied many times and in any order, so the method expresses moved and repeated text directly, which an edit distance or a line diff such as Heckel's algorithm cannot do. It is the model of copy and add deltas, and the same parse as LZ77 when the copies come from a separate source instead of the text already written. This kind of file delta is a different thing from delta encoding of numbers. In block edit distance the blocks of the source can be used only once, and that problem is much harder.

In plain words

You have an old text and a new text, and you want to describe the new text with as few instructions as possible. An instruction either says "copy this many characters from that place in the old text", or "add this character", for a character that the old text does not have.

Start at the beginning of the new text. Find the longest piece of the old text that matches the new text here, and copy it. Then do the same at the position after the copy. If no piece matches, the character is new, so add it.

Taking the longest copy each time is always best. A shorter copy can never let a later copy reach further.

The problem

The input is a source S=S[0…m−1]S = S[0 \ldots m - 1] and a target T=T[0…n−1]T = T[0 \ldots n - 1] over some alphabet. A move is a copy (p,ℓ)(p, \ell) with ℓ≥1\ell \ge 1, which appends S[p…p+ℓ−1]S[p \ldots p + \ell - 1], or an add of one symbol. A cover of TT is a list of moves that, run in order, produce TT. The goal is a cover with the fewest moves. Tichy calls the copied blocks a covering set of common substrings of TT with respect to SS. Every symbol of TT that does not occur in SS needs an add, and other symbols can always be copied, so the goal is the same as the fewest copies.

The algorithm

  1. BLOCK-MOVES(S[0 .. m - 1], T[0 .. n - 1])
  2. 1q ← 0; M ← an empty list
  3. 2while q < n do
  4. 3for p ← 0 to m - 1 do ℓ_p ← the length of the longest common prefix of S[p .. m - 1] and T[q .. n - 1]
  5. 4ℓ ← the largest ℓ_p, and p* ← the first p with ℓ_p = ℓ
  6. 5if ℓ = 0 then append add(T[q]) to M; q ← q + 1 ▷ T[q] does not occur in S
  7. 6else append copy(p*, ℓ) to M; q ← q + ℓ
  8. 7return M

Lines L3 and L4 find the longest prefix of the rest of TT that occurs in SS, by comparing it with each suffix of SS. Tichy also gives a linear version: build a suffix tree of SS, and walk it along T[q…]T[q \ldots] until the next symbol has no branch. The implementation of this page has the direct version and a linear version with the suffix automaton of SS, which accepts exactly the substrings of SS. Both take the first occurrence on ties, so they return the same moves.

Example

Take S=abcdeS = abcde and T=cdeabxeT = cdeabxe.

qq rest of TT longest prefix found in SS move
0 cdeabxe cde, at p=2p = 2 copy(2, 3)
3 abxe ab, at p=0p = 0 copy(0, 2)
5 xe none, xx is not in SS add(x)
6 e e, at p=4p = 4 copy(4, 1)

The result has 4 moves: three copies and the add that xx needs. The block cde moved in front of ab, and the cover says so with two copies. A diff that only deletes and inserts symbols keeps a longest common subsequence, here of length 3, such as cde, and needs 5+7−2⋅3=65 + 7 - 2 \cdot 3 = 6 operations, with ab deleted at one place and inserted at another.

Copies may repeat and overlap in the source: for S=abS = ab and T=abababT = ababab the cover is copy(0, 2) three times.

Correctness

The proof file uses the method of greedy stays ahead. Let G(q)G(q) be the position after the greedy move at qq. Any move of any cover that starts at qq ends at most at G(q)G(q), because a copy produces a substring of SS that starts at qq, and line L4 takes the longest one. And GG is monotone: if q≤q′q \le q' then G(q)≤G(q′)G(q) \le G(q'), since every substring of a block of SS is also a block of SS. So by induction, after ii moves the greedy cover is at least as far along TT as any other cover after ii moves, and it reaches the end of TT with no more moves than the best cover. The moves are valid because each one produces the next part of TT, and the adds are exactly the symbols of TT that are not in SS.

Proof: The greedy longest copy at each position builds the target with the fewest movesfull

We use the pseudocode of the page. The source is SS with ∣S∣=m|S| = m and the target is TT with ∣T∣=n|T| = n, indexed from 0. A move is a copy (p,ℓ)(p, \ell) with ℓ≥1\ell \ge 1, which appends S[p…p+ℓ−1]S[p \ldots p + \ell - 1], or an add of one symbol. A cover of TT is a list of moves whose outputs, joined in order, give TT. Each move of a cover produces a segment T[q…r−1]T[q \ldots r - 1] of TT; we say that it goes from qq to rr. The cost of a cover is its number of moves.

For a position q<nq < n, let L(q)L(q) be the length of the longest prefix of T[q…n−1]T[q \ldots n - 1] that occurs in SS as a substring, and let G(q)=q+max⁡(1,L(q))G(q) = q + \max(1, L(q)).

Lemma 1 (closure). If T[q…r−1]T[q \ldots r - 1] occurs in SS, then every substring T[q′…r′−1]T[q' \ldots r' - 1] with q≤q′<r′≤rq \le q' < r' \le r occurs in SS.

Proof. If T[q…r−1]=S[p…p+r−q−1]T[q \ldots r - 1] = S[p \ldots p + r - q - 1], then T[q′…r′−1]=S[p+q′−q…p+r′−q−1]T[q' \ldots r' - 1] = S[p + q' - q \ldots p + r' - q - 1]. □\square

Lemma 2 (the greedy step). Lines L3 to L6, run at position qq, append one move from qq to G(q)G(q). Every move of any cover that starts at qq ends at most at G(q)G(q).

Proof. Line L3 computes, for each start pp in SS, the length of the longest common prefix of S[p…m−1]S[p \ldots m - 1] and T[q…n−1]T[q \ldots n - 1], and line L4 keeps the largest. A prefix of T[q…]T[q \ldots] occurs in SS exactly when it is a common prefix of T[q…]T[q \ldots] and some S[p…]S[p \ldots], so the largest value is L(q)L(q). If L(q)=0L(q) = 0, the symbol T[q]T[q] does not occur in SS, and line L5 appends an add from qq to q+1=G(q)q + 1 = G(q). Otherwise line L6 appends the copy (p,L(q))(p, L(q)) with S[p…p+L(q)−1]=T[q…q+L(q)−1]S[p \ldots p + L(q) - 1] = T[q \ldots q + L(q) - 1], from qq to G(q)G(q). For the second claim: an add from qq ends at q+1≤G(q)q + 1 \le G(q), and a copy from qq to rr produces T[q…r−1]T[q \ldots r - 1] as a substring of SS, so r−q≤L(q)r - q \le L(q) and r≤G(q)r \le G(q). □\square

Lemma 3 (monotone). If q≤q′<nq \le q' < n, then G(q)≤G(q′)G(q) \le G(q').

Proof. If q′≥G(q)q' \ge G(q), then G(q′)>q′≥G(q)G(q') > q' \ge G(q). Otherwise q≤q′<G(q)q \le q' < G(q). If L(q)=0L(q) = 0, then G(q)=q+1G(q) = q + 1 and q′=qq' = q. If L(q)≥1L(q) \ge 1, then T[q…G(q)−1]T[q \ldots G(q) - 1] occurs in SS, so by Lemma 1 the prefix T[q′…G(q)−1]T[q' \ldots G(q) - 1] of T[q′…]T[q' \ldots] occurs in SS, and q′+L(q′)≥G(q)q' + L(q') \ge G(q). □\square

Theorem 1 (valid). The moves returned at line L7 build TT from SS.

Proof. The loop of line L2 keeps the invariant that the moves so far build T[0…q−1]T[0 \ldots q - 1]. It holds at q=0q = 0 by line L1. By Lemma 2, one round appends a move that produces T[q…G(q)−1]T[q \ldots G(q) - 1] and sets qq to G(q)G(q), so the invariant holds again. Since G(q)>qG(q) > q, the loop ends, at q=nq = n, and the moves build TT. □\square

Theorem 2 (fewest moves). No cover of TT has fewer moves than the greedy cover.

Proof. The method of greedy stays ahead. Let a cover have kk moves, ending at r1<r2<…<rk=nr_1 < r_2 < \ldots < r_k = n, and let the greedy moves end at g1<g2<…g_1 < g_2 < \ldots. We show gi≥rig_i \ge r_i for each i≤ki \le k for which the greedy cover still has an ii-th move, by induction on ii. For i=1i = 1, both first moves start at 0, so r1≤G(0)=g1r_1 \le G(0) = g_1 by Lemma 2. Assume gi≥rig_i \ge r_i and gi<ng_i < n. The (i+1)(i + 1)-th move of the cover goes from rir_i to ri+1r_{i + 1}, so by Lemmas 2 and 3, ri+1≤G(ri)≤G(gi)=gi+1r_{i + 1} \le G(r_i) \le G(g_i) = g_{i + 1}. So the greedy cover reaches nn no later than its kk-th move: it has at most kk moves. □\square

Adds are forced. By Lemma 2, line L5 adds a symbol only when it does not occur in SS. Every cover must produce such a symbol with an add, so the greedy cover has the least possible number of adds, and by Theorem 2 also the least number of moves in total, which is the least number of copies plus the forced adds.

The linear version. The suffix automaton of SS accepts exactly the substrings of SS when every state is accepting, so walking it along T[q…]T[q \ldots] until a transition is missing reads exactly L(q)L(q) symbols. All the strings that reach one state have the same set of end positions in SS, and the first end position of the state where the walk stops gives the start of the first occurrence of T[q…q+L(q)−1]T[q \ldots q + L(q) - 1]. So the linear version appends the same moves as lines L3 to L6, and the theorems apply to it.

Cost. In the direct version, line L3 at position qq compares at most L(q)+1L(q) + 1 pairs for each of the mm starts, so one round costs O(m(L(q)+1))O(m (L(q) + 1)). The rounds advance qq by max⁡(1,L(q))\max(1, L(q)), which sums to nn, so the total is O(mn)O(m n). In the linear version, the automaton has O(m)O(m) states and is built in O(m)O(m) expected time with hash tables for the transitions, and each round reads L(q)L(q) symbols plus one failed lookup, O(n)O(n) in total.

Complexity

Count in the word-RAM, with symbols compared in O(1)O(1).

  • Time, direct. At position qq, line L3 compares at most L+1L + 1 pairs for each of the mm starts, where LL is the length of the copy that follows; then qq moves by at least max⁡(1,L)\max(1, L). Over the whole target this is O(mn)O(m n).
  • Time, linear. A suffix tree or a suffix automaton of SS is built in O(m)O(m) time for a fixed alphabet, or expected time with hash tables for the edges. Each round reads the symbols of its copy plus one failed step, so the scan of TT is O(n)O(n), and the total is O(m+n)O(m + n).
  • Space. The direct version needs O(1)O(1) space besides the inputs and the list of moves. The linear version needs O(m)O(m) for the index.

Properties

  • Optimal. The greedy cover has the fewest moves, and so the fewest copies.
  • Online in the target. The method reads TT from left to right and writes each move as soon as it is found, so the target can be streamed through.
  • Moves and repeats. A block of SS can be copied any number of times, in any order, so moved and duplicated text costs one copy per block.
  • Deletes are free. Parts of SS that no copy uses are dropped without a move.
  • Not unique. Ties between starts change only where the copies come from, not their number or lengths.

Variants and improvements

  • Costs per move. A real delta encodes a copy with an offset and a length, and an add with its symbols. If a copy costs more than an add of one symbol, short copies may not pay off, and the greedy count of moves is no longer the right measure of size. Delta formats then use a minimum copy length.
  • Each block used once. If each part of SS may be used by at most one copy, the problem is the block edit distance family, where many versions are NP-hard.
  • Copies from the target itself. Allowing copies from the part of TT already written turns the method into a parse of the LZ77 kind, with SS as a dictionary in front of the text.
  • Fingerprints instead of an index. Delta tools for large files find candidate blocks by hashing fixed windows with a rolling checksum, as rsync does, and then extend each match. This finds long copies quickly but not always the longest.
  • Line units. The same rule works with lines or tokens as symbols, which gives a diff that reports moved blocks of lines.

When to use it

Use it to store or send a new version of a file as a delta against an old version, when moved and repeated blocks are common, for example in binary files, generated files and reordered source. Use a suffix automaton or a suffix tree for large inputs. For a delta that people read line by line, use a line diff such as Myers' algorithm; for a measure in which text may move but not be copied twice, see block edit distance.

Pitfalls

  • Overlapping copies. Two copies of the cover may take the same or overlapping blocks of SS. A decoder that assumes disjoint blocks fails.
  • Ties. The direct version and an index may pick different occurrences on ties. Tests should compare the lengths, or fix the rule, as this page does with the first occurrence.
  • Cost model. The theorem counts moves. When copies are encoded with more bytes than adds, a cover with fewest moves can be larger than another cover.
  • Quadratic time. The direct version is O(mn)O(m n) even when the delta is short. Long inputs need the linear version or fingerprints.

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.

tichy_block_moves.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tichy-block-moves/. The authors are listed in prov/ZJTFAN.jsonl.
"""Tichy's greedy covering of a target string by block moves from a source (TOCS 2(4), 1984).

A block move ("copy", p, l) appends s[p:p + l] to the output. An add ("add", x)
appends the symbol x, which is needed when x does not occur in s. The greedy
method takes, at each position of t, the longest prefix of the rest of t that
occurs in s. The function block_moves does this with direct comparisons in
O(|s| |t|) time; block_moves_linear finds the same lengths with a suffix
automaton of s in linear expected time.
"""

from collections.abc import Sequence
from typing import Any

Move = tuple  # ("copy", p, l) or ("add", x)


def block_moves(s: Sequence[Any], t: Sequence[Any]) -> list[Move]:
    """Return a shortest list of copies and adds that builds t from s, by the greedy rule."""
    moves: list[Move] = []
    q = 0  # @line L1
    while q < len(t):  # @line L2
        best_p, best_l = -1, 0
        for p in range(len(s)):  # @line L3
            l = 0
            while p + l < len(s) and q + l < len(t) and s[p + l] == t[q + l]:
                l += 1
            if l > best_l:  # @line L4
                best_p, best_l = p, l
        if best_l == 0:  # @line L5
            moves.append(("add", t[q]))
            q += 1
        else:
            moves.append(("copy", best_p, best_l))  # @line L6
            q += best_l
    return moves  # @line L7


class _SuffixAutomaton:
    """The suffix automaton of s, with the end of the first occurrence for each state."""

    def __init__(self, s: Sequence[Any]) -> None:
        self.next: list[dict[Any, int]] = [{}]
        self.link = [-1]
        self.length = [0]
        self.first_end = [-1]
        last = 0
        for i, x in enumerate(s):
            cur = self._new(self.length[last] + 1, i)
            v = last
            while v != -1 and x not in self.next[v]:
                self.next[v][x] = cur
                v = self.link[v]
            if v == -1:
                self.link[cur] = 0
            else:
                w = self.next[v][x]
                if self.length[v] + 1 == self.length[w]:
                    self.link[cur] = w
                else:
                    clone = self._new(self.length[v] + 1, self.first_end[w])
                    self.next[clone] = dict(self.next[w])
                    self.link[clone] = self.link[w]
                    while v != -1 and self.next[v].get(x) == w:
                        self.next[v][x] = clone
                        v = self.link[v]
                    self.link[w] = self.link[cur] = clone
            last = cur

    def _new(self, length: int, first_end: int) -> int:
        self.next.append({})
        self.link.append(-1)
        self.length.append(length)
        self.first_end.append(first_end)
        return len(self.length) - 1


def block_moves_linear(s: Sequence[Any], t: Sequence[Any]) -> list[Move]:
    """Return the greedy moves, with each longest prefix found by walking the suffix automaton of s."""
    sam = _SuffixAutomaton(s)
    moves: list[Move] = []
    q = 0
    while q < len(t):
        v, l = 0, 0
        while q + l < len(t) and t[q + l] in sam.next[v]:
            v = sam.next[v][t[q + l]]
            l += 1
        if l == 0:
            moves.append(("add", t[q]))
            q += 1
        else:
            moves.append(("copy", sam.first_end[v] - l + 1, l))
            q += l
    return moves


def apply_moves(s: Sequence[Any], moves: Sequence[Move]) -> list[Any]:
    """Return the sequence that the moves build from s."""
    out: list[Any] = []
    for move in moves:
        if move[0] == "copy":
            _, p, l = move
            if not (0 <= p and l >= 1 and p + l <= len(s)):
                raise ValueError(f"bad copy {move}")
            out.extend(s[p:p + l])
        elif move[0] == "add":
            out.append(move[1])
        else:
            raise ValueError(f"bad move {move}")
    return out
test_tichy_block_moves.py 57 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/tichy-block-moves/. The authors are listed in prov/ZJTFAN.jsonl.

import itertools
import random

from tichy_block_moves import apply_moves, block_moves, block_moves_linear


def fewest_moves(s, t):
    """The least number of copies and adds that build t, by a dynamic program over the positions of t."""
    subs = {tuple(s[i:j]) for i in range(len(s)) for j in range(i + 1, len(s) + 1)}
    best = [0] * (len(t) + 1)
    for q in range(len(t) - 1, -1, -1):
        best[q] = 1 + best[q + 1]
        for r in range(q + 1, len(t) + 1):
            if tuple(t[q:r]) in subs:
                best[q] = min(best[q], 1 + best[r])
    return best[0]


def test_page_example() -> None:
    s, t = "abcde", "cdeabxe"
    moves = block_moves(s, t)
    assert moves == [("copy", 2, 3), ("copy", 0, 2), ("add", "x"), ("copy", 4, 1)]
    assert "".join(apply_moves(s, moves)) == t
    assert block_moves_linear(s, t) == moves


def test_copies_may_repeat_and_overlap() -> None:
    assert block_moves("ab", "ababab") == [("copy", 0, 2)] * 3
    assert block_moves("aaa", "aaaaa") == [("copy", 0, 3), ("copy", 0, 2)]
    assert block_moves("", "xy") == [("add", "x"), ("add", "y")]
    assert block_moves("abc", "") == []


def test_greedy_is_optimal_on_all_small_inputs() -> None:
    words = [w for n in range(8) for w in itertools.product("ab", repeat=n)]
    for s in words:
        for t in words:
            moves = block_moves(s, t)
            assert tuple(apply_moves(s, moves)) == t
            assert len(moves) == fewest_moves(s, t)


def test_random_inputs() -> None:
    rng = random.Random(17)
    for _ in range(300):
        alpha = "abcdxyz"[: rng.randint(1, 7)]
        s = [rng.choice(alpha[:4]) for _ in range(rng.randint(0, 15))]
        t = [rng.choice(alpha) for _ in range(rng.randint(0, 15))]
        moves = block_moves(s, t)
        assert apply_moves(s, moves) == t
        assert block_moves_linear(s, t) == moves
        assert len(moves) == fewest_moves(s, t)
        # An add is used only for a symbol that does not occur in s.
        assert all(m[1] not in s for m in moves if m[0] == "add")

History

Walter Tichy, at Purdue University, wrote the method in a technical report in 1983 and published it in ACM Transactions on Computer Systems in 1984. He set it against the diff programs of the time, which compute a longest common subsequence, and showed that block moves give a cover with the fewest blocks by a simple greedy rule, in linear time with a suffix tree. Copy and add deltas of this kind are used in later delta formats and version control storage.

References

  1. Walter F. Tichy, The string-to-string correction problem with block moves, ACM Transactions on Computer Systems 2(4), 1984, 309-321, the block move model, the minimal covering set of common substrings, the greedy longest match at each position with its proof of minimality, the O(mn) method and the linear method with a suffix tree
  2. Walter F. Tichy, The string-to-string correction problem with block moves, Purdue University, Department of Computer Science technical report, 1983, the earlier report version of the paper

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
  • History with a source
  • at least three sources
  • a scene preset for the example