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
- Model
- Word RAM
- Properties
- deterministicgreedyonlineiterative
- Evidence
- Proof sketchCode in 1 languages
Tichy's block move algorithm writes a target string as a list of moves: a copy of a block of the source string , or an add of one symbol that does not occur in . At each position of it takes the longest block of that matches there. Walter Tichy proved in 1984 that this greedy rule gives the fewest moves. A block of 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 and a target over some alphabet. A move is a copy with , which appends , or an add of one symbol. A cover of is a list of moves that, run in order, produce . The goal is a cover with the fewest moves. Tichy calls the copied blocks a covering set of common substrings of with respect to . Every symbol of that does not occur in needs an add, and other symbols can always be copied, so the goal is the same as the fewest copies.
The algorithm
BLOCK-MOVES(S[0 .. m - 1], T[0 .. n - 1])- 1
q ← 0; M ← an empty list - 2
while q < n do - 3
for p ← 0 to m - 1 do ℓ_p ← the length of the longest common prefix of S[p .. m - 1] and T[q .. n - 1] - 4
ℓ ← the largest ℓ_p, and p* ← the first p with ℓ_p = ℓ - 5
if ℓ = 0 then append add(T[q]) to M; q ← q + 1 ▷ T[q] does not occur in S - 6
else append copy(p*, ℓ) to M; q ← q + ℓ - 7
return M
Lines L3 and L4 find the longest prefix of the rest of that occurs in , by comparing it with each suffix of . Tichy also gives a linear version: build a suffix tree of , and walk it along 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 , which accepts exactly the substrings of . Both take the first occurrence on ties, so they return the same moves.
Example
Take and .
| rest of | longest prefix found in | move | |
|---|---|---|---|
| 0 | cdeabxe | cde, at | copy(2, 3) |
| 3 | abxe | ab, at | copy(0, 2) |
| 5 | xe | none, is not in | add(x) |
| 6 | e | e, at | copy(4, 1) |
The result has 4 moves: three copies and the add that 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 operations, with ab deleted at one place and inserted at another.
Copies may repeat and overlap in the source: for and the cover is copy(0, 2) three times.
Correctness
The proof file uses the method of greedy stays ahead. Let be the position after the greedy move at . Any move of any cover that starts at ends at most at , because a copy produces a substring of that starts at , and line L4 takes the longest one. And is monotone: if then , since every substring of a block of is also a block of . So by induction, after moves the greedy cover is at least as far along as any other cover after moves, and it reaches the end of with no more moves than the best cover. The moves are valid because each one produces the next part of , and the adds are exactly the symbols of that are not in .
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 with and the target is with , indexed from 0. A move is a copy with , which appends , or an add of one symbol. A cover of is a list of moves whose outputs, joined in order, give . Each move of a cover produces a segment of ; we say that it goes from to . The cost of a cover is its number of moves.
For a position , let be the length of the longest prefix of that occurs in as a substring, and let .
Lemma 1 (closure). If occurs in , then every substring with occurs in .
Proof. If , then .
Lemma 2 (the greedy step). Lines L3 to L6, run at position , append one move from to . Every move of any cover that starts at ends at most at .
Proof. Line L3 computes, for each start in , the length of the longest common prefix of and , and line L4 keeps the largest. A prefix of occurs in exactly when it is a common prefix of and some , so the largest value is . If , the symbol does not occur in , and line L5 appends an add from to . Otherwise line L6 appends the copy with , from to . For the second claim: an add from ends at , and a copy from to produces as a substring of , so and .
Lemma 3 (monotone). If , then .
Proof. If , then . Otherwise . If , then and . If , then occurs in , so by Lemma 1 the prefix of occurs in , and .
Theorem 1 (valid). The moves returned at line L7 build from .
Proof. The loop of line L2 keeps the invariant that the moves so far build . It holds at by line L1. By Lemma 2, one round appends a move that produces and sets to , so the invariant holds again. Since , the loop ends, at , and the moves build .
Theorem 2 (fewest moves). No cover of has fewer moves than the greedy cover.
Proof. The method of greedy stays ahead. Let a cover have moves, ending at , and let the greedy moves end at . We show for each for which the greedy cover still has an -th move, by induction on . For , both first moves start at 0, so by Lemma 2. Assume and . The -th move of the cover goes from to , so by Lemmas 2 and 3, . So the greedy cover reaches no later than its -th move: it has at most moves.
Adds are forced. By Lemma 2, line L5 adds a symbol only when it does not occur in . 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 accepts exactly the substrings of when every state is accepting, so walking it along until a transition is missing reads exactly symbols. All the strings that reach one state have the same set of end positions in , and the first end position of the state where the walk stops gives the start of the first occurrence of . 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 compares at most pairs for each of the starts, so one round costs . The rounds advance by , which sums to , so the total is . In the linear version, the automaton has states and is built in expected time with hash tables for the transitions, and each round reads symbols plus one failed lookup, in total.
Complexity
Count in the word-RAM, with symbols compared in .
- Time, direct. At position , line L3 compares at most pairs for each of the starts, where is the length of the copy that follows; then moves by at least . Over the whole target this is .
- Time, linear. A suffix tree or a suffix automaton of is built in 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 is , and the total is .
- Space. The direct version needs space besides the inputs and the list of moves. The linear version needs for the index.
Properties
- Optimal. The greedy cover has the fewest moves, and so the fewest copies.
- Online in the target. The method reads 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 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 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 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 already written turns the method into a parse of the LZ77 kind, with 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 . 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 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.
# 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
- 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
- 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.
| 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 ZJTFAN Edit this page History Report an error Markdown