List Update and Move-to-Front
Keep a set of items in an unsorted linked list and look them up by scanning from the front. Finding the item in position costs steps, so frequently requested items should sit near the front. Which ones are frequent is not known in advance, and it may change over time. The list update problem asks how to reorganize the list online, and its simplest answer, move-to-front, comes with one of the most elegant proofs in competitive analysis: a potential function that counts disagreements with the optimal list.
The cost model
The list holds items. A request for the item in position (counting from 1) costs . Right after the access, the item may be moved any distance toward the front for free (a free exchange: the pointer is already there); any other swap of two adjacent items costs 1 (a paid exchange). Three natural online rules:
- Move-to-front (MTF): move the requested item to the front.
- Transpose: swap the requested item with the one just before it.
- Frequency count (FC): keep a counter per item and keep the list sorted by decreasing count.
All three use only free exchanges. The program runs them on a short sequence over five items.
def mtf(lst, x):
lst.remove(x); lst.insert(0, x)
def transpose(lst, x):
i = lst.index(x)
if i > 0:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
def make_fc():
counts = {}
def fc(lst, x):
counts[x] = counts.get(x, 0) + 1
i = lst.index(x)
while i > 0 and counts.get(lst[i - 1], 0) < counts[x]: # move past smaller counts
lst[i - 1], lst[i] = lst[i], lst[i - 1]
i -= 1
return fc
def serve(rule, start, requests, show=False):
lst, cost = list(start), 0
for x in requests:
cost += lst.index(x) + 1
rule(lst, x)
if show:
print(f" {x}: {''.join(lst)}")
return cost
start, requests = "abcde", "eedaeedcae"
print("move-to-front:")
c1 = serve(mtf, start, requests, show=True)
print("costs: MTF", c1, " transpose", serve(transpose, start, requests),
" frequency count", serve(make_fc(), start, requests))move-to-front:
e: eabcd
e: eabcd
d: deabc
a: adebc
e: eadbc
e: eadbc
d: deabc
c: cdeab
a: acdeb
e: eacdb
costs: MTF 34 transpose 33 frequency count 27
Transpose and frequency count can be terrible
Transpose looks cautious and sensible, but an adversary defeats it easily: request the last two items alternately. Each request swaps them, so each one sits at position or forever. MTF puts both at the front after two requests. Frequency count fails differently: a burst of requests for an item gives it a count that keeps it near the front long after it stops being used.
def mtf(lst, x):
lst.remove(x); lst.insert(0, x)
def transpose(lst, x):
i = lst.index(x)
if i > 0:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
def make_fc():
counts = {}
def fc(lst, x):
counts[x] = counts.get(x, 0) + 1
i = lst.index(x)
while i > 0 and counts.get(lst[i - 1], 0) < counts[x]:
lst[i - 1], lst[i] = lst[i], lst[i - 1]
i -= 1
return fc
def serve(rule, start, requests):
lst, cost = list(start), 0
for x in requests:
cost += lst.index(x) + 1
rule(lst, x)
return cost
n = 10
start = [f"x{i}" for i in range(n)]
alternate = [start[-1], start[-2]] * 50 # 100 requests
phases = [start[0]] * 50 + [start[n - 1 - k] for k in range(n - 1) for _ in range(5)]
for name, seq in [("alternate last two", alternate), ("burst, then others", phases)]:
print(f"{name:19} ({len(seq)} requests): MTF {serve(mtf, start, seq):4}, "
f"transpose {serve(transpose, start, seq):4}, FC {serve(make_fc(), start, seq):4}")alternate last two (100 requests): MTF 216, transpose 1000, FC 167
burst, then others (95 requests): MTF 176, transpose 323, FC 356
On the alternating sequence transpose pays almost per request while MTF pays about 2. On the second sequence, item x0 is requested 50 times and then never again; frequency count keeps it at the front while the other items fight over the positions behind it, and transpose needs many requests before each new item reaches the front. MTF adapts at once.
MTF is 2-competitive
Theorem (Sleator and Tarjan, 1985). For every request sequence and every algorithm for list update (online or offline) that starts from the same list, , where 's cost includes its paid exchanges. In particular MTF is 2-competitive.
The proof is an amortized analysis with the potential method (The Potential Method). The potential compares MTF's list with 's list:
the pairs of items that appear in opposite orders in the two lists. It starts at 0 and is never negative.
Proof
Consider a request for item , at position in MTF's list and position in 's list. Of the items in front of in MTF's list, say are behind in 's list and are in front of it there too. The items in front of in both lists number at most , so .
Moving to the front removes the inversions it had with those items and creates new ones (with the items that are in front of in 's list), so . The amortized cost of MTF's access is
Then rearranges its own list. A free exchange moves forward, past items that are now behind in MTF's list, so it can only remove inversions. Each paid exchange changes the order of one pair, so it raises by at most 1 while costing 1.
So for each request, MTF's amortized cost is at most where pays ( paid exchanges). Summing, , where is the number of requests.
The program checks the key inequality, amortized cost at most , at every step, with the best static list for the sequence (found by trying every order of five items).
from itertools import permutations
def inversions(a, b):
pos = {x: i for i, x in enumerate(b)}
seq = [pos[x] for x in a]
return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j])
start = "abcde"
requests = "eedaeedcaebbedaeeabe"
def static_cost(order):
return sum(order.index(x) + 1 for x in requests)
# a static list that is rearranged once, before the first request, with paid exchanges
best = min(("".join(p) for p in permutations(start)),
key=lambda o: static_cost(o) + inversions(o, start))
setup = inversions(best, start)
print("best static list", best, "with", setup, "paid exchanges, then cost", static_cost(best))
mtf, total, ok = list(start), 0, True
phi = inversions(mtf, best) # A has already rearranged its list
for x in requests:
k, i = mtf.index(x) + 1, best.index(x) + 1
mtf.remove(x); mtf.insert(0, x)
new_phi = inversions(mtf, best)
ok &= k + (new_phi - phi) <= 2 * i - 1
phi, total = new_phi, total + k
opt = static_cost(best) + setup
print("MTF cost", total, " A cost", opt, " ratio", round(total / opt, 3))
print("amortized cost <= 2i - 1 at every step:", ok, " MTF <= 2A:", total <= 2 * opt)best static list eabdc with 5 paid exchanges, then cost 43
MTF cost 64 A cost 48 ratio 1.333
amortized cost <= 2i - 1 at every step: True MTF <= 2A: True
A lower bound
No deterministic online algorithm is better than about 2. The adversary always requests the item at the end of the algorithm's list, so every request costs . Over requests the algorithm pays . An offline algorithm can do no worse than the best static list for the sequence, and averaging over all static lists, the expected cost of a request is , so some list pays at most plus a one-time rearrangement. The ratio tends to .
In C++
MTF has a second life as a data transform: replace each symbol by its current position in the list, then move it to the front. Runs of repeated symbols become runs of zeros, which compress well; the Burrows-Wheeler compressor bzip2 uses exactly this step. The C++ program encodes a string, decodes it again and reports the total access cost, which is the sum of the positions plus one per symbol.
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>
int main() {
std::string text = "bananaaaabbbbanana";
std::vector<char> list = {'a', 'b', 'n'};
std::vector<int> code;
long long cost = 0;
for (char c : text) {
int pos = int(std::find(list.begin(), list.end(), c) - list.begin());
code.push_back(pos);
cost += pos + 1;
list.erase(list.begin() + pos);
list.insert(list.begin(), c); // move to front
}
std::printf("encoded:");
for (int p : code) std::printf(" %d", p);
std::printf("\n");
std::vector<char> back = {'a', 'b', 'n'};
std::string decoded;
for (int p : code) {
char c = back[p];
decoded += c;
back.erase(back.begin() + p);
back.insert(back.begin(), c);
}
std::printf("decoded: %s (%s)\n", decoded.c_str(), decoded == text ? "matches" : "differs");
std::printf("MTF access cost %lld for %zu requests\n", cost, text.size());
}encoded: 1 1 2 1 1 1 0 0 0 2 0 0 0 1 2 1 1 1
decoded: bananaaaabbbbanana (matches)
MTF access cost 33 for 18 requests
Self-adjusting structures beyond lists follow the same idea: splay trees move every accessed key to the root and are, by a similar potential argument, as good as any static binary search tree up to a constant factor. Competitive analysis of list update, including randomized algorithms that beat 2, continues in Online Algorithms & Competitive Analysis.
Test yourself
The list is a b c d e. What does MTF pay for the requests e, e, d?
Which request sequence makes transpose pay about per request while MTF pays about 2?
- Always the first item
- Alternating between the last two items
- Items in sorted order
- Each item once
What is the potential function in the proof that MTF is 2-competitive?
- The length of the list
- The number of inversions between MTF's list and the other algorithm's list
- The total cost so far
- The position of the most frequent item
Why can no deterministic online list-update algorithm be better than about 2-competitive?
- Because accesses cost at least 1
- Because an adversary can always request the last item, costing each time, while a good static list averages about
- Because MTF is optimal offline
- Because paid exchanges are free