List Update: Move-to-Front, Transpose and Frequency Count
List Update and Move-to-Front introduced the problem and the potential-function proof that move-to-front (MTF) is 2-competitive. This lesson revisits the proof in the full cost model and checks its key inequality step by step against an arbitrary competitor, proves that transpose and frequency count are not competitive at all, and goes beyond deterministic algorithms: the randomized algorithm BIT beats every deterministic one against an oblivious adversary.
The full cost model
A list holds items. Accessing the item at position (from 1) costs . Immediately after an access, the accessed item may be moved any distance towards the front at no cost (free exchanges). Any other swap of two adjacent items costs 1 (paid exchanges). This is the model of Sleator and Tarjan (1985). Three classical online rules use only free exchanges:
| Rule | After accessing |
|---|---|
| move-to-front (MTF) | move to the front |
| transpose (TRANS) | swap with the item just in front of it |
| frequency count (FC) | keep the list sorted by access counts, decreasing; move forward past items with smaller counts |
Computing the offline optimum is hard: Ambühl (2000) proved that offline list update is NP-hard. Competitive analysis therefore compares with any offline algorithm, without knowing the optimal one, which is exactly what the potential argument allows.
MTF against any algorithm
Theorem (Sleator and Tarjan, 1985). Let be any algorithm, online or offline, that starts from the same list as MTF and serves the requests of , paying for its accesses and its paid exchanges. Then
Proof
Let the potential be the number of inversions between MTF's list and 's list: pairs of items in different relative order in the two lists. Initially , and always .
Consider a request for , at position in MTF's list and position in 's list. Of the items in front of in MTF's list, let be the number that are behind in 's list; the other are in front of in both lists, so . Moving to the front removes inversions and creates , so MTF's amortized cost is
Now let serve the request. A free exchange moves forward in 's list; is at the front of MTF's list, so this can only remove inversions. Each paid exchange changes the order of one pair and raises by at most 1, while costing exactly 1. So for each request with paid exchanges, . Summing over all requests and using gives the theorem.
The program checks the per-request inequality on a seeded random sequence, with = transpose as the competitor (any algorithm works).
import random
def inversions(a, b):
pos = {x: i for i, x in enumerate(b)}
seq = [pos[x] for x in a]
return sum(seq[i] > seq[j] for i in range(len(seq)) for j in range(i + 1, len(seq)))
rng = random.Random(4)
items = list("abcdefgh")
mtf, trans = items[:], items[:]
phi, worst_slack, total_mtf, total_a = 0, None, 0, 0
for t in range(300):
x = rng.choice("aaabbcdefgh") # a few items are more popular
k, i = mtf.index(x) + 1, trans.index(x) + 1
mtf.insert(0, mtf.pop(k - 1)) # MTF: move to front
if i > 1: # transpose: swap with predecessor (free)
trans[i - 2], trans[i - 1] = trans[i - 1], trans[i - 2]
new_phi = inversions(mtf, trans)
slack = (2 * i - 1) - (k + new_phi - phi) # >= 0 by the theorem
worst_slack = slack if worst_slack is None else min(worst_slack, slack)
phi, total_mtf, total_a = new_phi, total_mtf + k, total_a + i
print(f"MTF {total_mtf}, TRANS {total_a}, 2*TRANS - m = {2 * total_a - 300}")
print(f"smallest slack in amortized cost + dPhi <= 2i - 1: {worst_slack} (never negative)")MTF 1177, TRANS 1068, 2*TRANS - m = 1836
smallest slack in amortized cost + dPhi <= 2i - 1: 0 (never negative)
In C++
MTF has a second use as a data transform in compression (bzip2 applies it after the Burrows-Wheeler transform), which Part I showed. Here the C++ program measures the three online rules on a seeded request stream whose popular items change halfway through, the situation where adapting quickly matters.
#include <algorithm>
#include <cstdio>
#include <random>
#include <vector>
int main() {
const int n = 50, m = 20000;
std::mt19937 rng(17);
std::vector<int> reqs;
for (int t = 0; t < m; ++t) {
int hot_base = t < m / 2 ? 0 : 25; // the hot set moves at half time
bool hot = rng() % 10 < 8;
reqs.push_back(hot ? hot_base + rng() % 5 : rng() % n);
}
std::vector<int> mtf(n), trans(n), fc(n), count(n, 0);
for (int i = 0; i < n; ++i) mtf[i] = trans[i] = fc[i] = i;
long long cm = 0, ct = 0, cf = 0;
for (int x : reqs) {
auto im = std::find(mtf.begin(), mtf.end(), x);
cm += im - mtf.begin() + 1;
std::rotate(mtf.begin(), im, im + 1); // move to front
auto it = std::find(trans.begin(), trans.end(), x);
ct += it - trans.begin() + 1;
if (it != trans.begin()) std::iter_swap(it, it - 1); // transpose
auto jf = std::find(fc.begin(), fc.end(), x);
cf += jf - fc.begin() + 1;
++count[x];
while (jf != fc.begin() && count[*(jf - 1)] < count[x]) { std::iter_swap(jf, jf - 1); --jf; }
}
std::printf("average access cost over %d requests: MTF %.2f, TRANS %.2f, FC %.2f\n",
m, double(cm) / m, double(ct) / m, double(cf) / m);
}average access cost over 20000 requests: MTF 8.42, TRANS 7.66, FC 9.55
Frequency count is the slowest: after the shift, the old hot items keep their large counts and block the front of the list. Transpose is actually the cheapest on this stream: once the hot items have crept forward it keeps them there, while MTF lets every cold request jump to the front and push the hot items back. Competitive ratios describe the worst case; on a benign stream the non-competitive rule can win, and the next section shows how badly it loses on a hostile one.
Transpose and frequency count are not competitive
Transpose. Request the last two items of TRANS's list alternately. Each access swaps them, so each request costs or , about per request. An offline algorithm moves both to the front once (cost about ) and then pays at most 2 per request. The ratio tends to as the sequence grows, so TRANS is not -competitive for any constant independent of .
Frequency count. Start from the list and request times, times, and so on, once. FC keeps the list in this order and pays . MTF pays for the first request to each and 1 for the repeats, about in total. Repeating such blocks (each time in the reverse of FC's current order) gives a ratio of order .
def serve(seq, items, rule):
lst, count, cost = items[:], {x: 0 for x in items}, 0
for x in seq:
i = lst.index(x)
cost += i + 1
count[x] += 1
if rule == "mtf":
lst.insert(0, lst.pop(i))
elif rule == "trans" and i > 0:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
elif rule == "fc":
while i > 0 and count[lst[i - 1]] < count[x]:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
i -= 1
return cost, lst
print(" n TRANS/MTF (alternating) FC/MTF (decreasing blocks)")
for n in [5, 10, 20, 40]:
items = list(range(n))
alternating = [n - 1, n - 2] * 200 # last two items of the start list
lst, blocks = items[:], []
for _ in range(4):
_, lst = serve(blocks, items, "fc")
order = lst[::-1] # request in the reverse of FC's order
blocks += [x for j, x in enumerate(order) for _ in range(n - j)]
ratios = [serve(alternating, items, "trans")[0] / serve(alternating, items, "mtf")[0],
serve(blocks, items, "fc")[0] / serve(blocks, items, "mtf")[0]]
print(f"{n:3} {ratios[0]:23.2f} {ratios[1]:26.2f}") n TRANS/MTF (alternating) FC/MTF (decreasing blocks)
5 2.48 2.00
10 4.90 3.12
20 9.57 5.35
40 18.26 9.80
Since MTF is within a factor 2 of OPT, a ratio over MTF of means a competitive ratio of at least ; both columns grow linearly in .
Randomization helps: BIT
BIT (Reingold, Westbrook and Sleator, 1994) gives every item a bit, set uniformly at random at the start. On each access the item's bit is flipped, and the item is moved to the front only when its bit becomes 1. So each item moves to the front on every second access, but the oblivious adversary does not know on which ones.
Theorem (Reingold, Westbrook and Sleator, 1994). BIT is -competitive against an oblivious adversary.
The best known randomized algorithm is COMB (Albers, von Stengel and Werchner, 1995), -competitive, and no randomized algorithm beats against an oblivious adversary (Teia, 1993); the exact randomized ratio is open. Deterministically, nothing beats (Karp and Raghavan; see Part I). The program runs MTF's cruel adversary, which always requests the last item of MTF's list, against MTF and against BIT with fixed seeds. To compare with OPT it uses an upper bound on OPT: the cheapest static list for the sequence (computed exactly by sorting items by frequency).
import random
def mtf_cruel(n, m):
lst, seq = list(range(n)), []
for _ in range(m):
x = lst[-1]
seq.append(x)
lst.insert(0, lst.pop())
return seq
def bit_cost(seq, n, rng):
lst = list(range(n))
bit = {x: rng.randrange(2) for x in lst}
cost = 0
for x in seq:
i = lst.index(x)
cost += i + 1
bit[x] ^= 1
if bit[x] == 1:
lst.insert(0, lst.pop(i))
return cost
def static_opt_bound(seq, n):
freq = {x: seq.count(x) for x in range(n)}
order = sorted(range(n), key=lambda x: -freq[x])
pos = {x: i + 1 for i, x in enumerate(order)}
rearrange = sum(1 for i in range(n) for j in range(i + 1, n) if pos[i] > pos[j]) # paid swaps
return sum(pos[x] for x in seq) + rearrange
n, m = 8, 4000
seq = mtf_cruel(n, m)
opt_ub = static_opt_bound(seq, n)
bits = [bit_cost(seq, n, random.Random(seed)) for seed in range(20)]
print(f"MTF's cruel sequence, n = {n}: MTF pays {n * m}, OPT <= {opt_ub}")
print(f"MTF / OPT-bound = {n * m / opt_ub:.3f} (2 - 2/(n+1) = {2 - 2 / (n + 1):.3f})")
print(f"BIT (20 seeds), mean / OPT-bound = {sum(bits) / len(bits) / opt_ub:.3f}")MTF's cruel sequence, n = 8: MTF pays 32000, OPT <= 18000
MTF / OPT-bound = 1.778 (2 - 2/(n+1) = 1.778)
BIT (20 seeds), mean / OPT-bound = 1.389
On MTF's worst sequence, BIT pays much less than MTF, because the adversary's sequence was built for MTF's deterministic moves. This does not prove BIT's ratio (an adversary would choose a different sequence against BIT), but it shows how randomization breaks the deterministic worst case.
Test yourself
In the potential proof, what is ?
- MTF's total cost so far
- The number of pairs of items whose relative order differs between MTF's list and the competitor's list
- The position of the requested item
- The number of paid exchanges
Item is at position 9 in MTF's list and position 3 in the competitor's list. What is the largest possible amortized cost of MTF's access?
Why is transpose not competitive?
- It uses paid exchanges
- Alternating requests to its last two items keep both at the back forever, costing about per request while OPT pays about 2
- It is randomized
- It never moves items
What are the known bounds for randomized list update against an oblivious adversary?
- Exactly 2
- Upper bound (COMB), lower bound ; the exact value is open
- Upper bound , lower bound
- It equals