TExcelTAD
Home › Online Algorithms & Competitive Analysis › List Update: Move-to-Front, Transpose and Frequency Count

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 nn items. Accessing the item at position ii (from 1) costs ii. 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 xx
move-to-front (MTF) move xx to the front
transpose (TRANS) swap xx with the item just in front of it
frequency count (FC) keep the list sorted by access counts, decreasing; move xx 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 AA be any algorithm, online or offline, that starts from the same list as MTF and serves the mm requests of σ\sigma, paying for its accesses and its paid exchanges. Then

MTF(σ)≤2 A(σ)−m.\mathrm{MTF}(\sigma) \le 2\,A(\sigma) - m .
Proof

Let the potential Φ\Phi be the number of inversions between MTF's list and AA's list: pairs of items in different relative order in the two lists. Initially Φ=0\Phi = 0, and always Φ≥0\Phi \ge 0.

Consider a request for xx, at position kk in MTF's list and position ii in AA's list. Of the k−1k - 1 items in front of xx in MTF's list, let vv be the number that are behind xx in AA's list; the other k−1−vk - 1 - v are in front of xx in both lists, so k−1−v≤i−1k - 1 - v \le i - 1. Moving xx to the front removes vv inversions and creates k−1−vk - 1 - v, so MTF's amortized cost is

k+(k−1−v)−v=2(k−1−v)+1≤2(i−1)+1=2i−1.k + (k - 1 - v) - v = 2(k - 1 - v) + 1 \le 2(i - 1) + 1 = 2i - 1 .

Now let AA serve the request. A free exchange moves xx forward in AA's list; xx 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 Φ\Phi by at most 1, while costing AA exactly 1. So for each request with pp paid exchanges, MTF’s cost+ΔΦ≤2i−1+p≤2(i+p)−1\text{MTF's cost} + \Delta\Phi \le 2i - 1 + p \le 2(i + p) - 1. Summing over all requests and using Φend≥0\Phi_{\text{end}} \ge 0 gives the theorem.

The program checks the per-request inequality cost+ΔΦ≤2⋅(A’s cost)−1\text{cost} + \Delta\Phi \le 2 \cdot (\text{A's cost}) - 1 on a seeded random sequence, with AA = transpose as the competitor (any algorithm works).

python · try it yourself
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.

cpp · try it yourself
#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 nn or n−1n - 1, about nn per request. An offline algorithm moves both to the front once (cost about 2n2n) and then pays at most 2 per request. The ratio tends to n/2n/2 as the sequence grows, so TRANS is not cc-competitive for any constant cc independent of nn.

Frequency count. Start from the list x1,…,xnx_1, \ldots, x_n and request x1x_1 nn times, x2x_2 n−1n - 1 times, and so on, xnx_n once. FC keeps the list in this order and pays ∑ii(n+1−i)≈n3/6\sum_i i(n + 1 - i) \approx n^3/6. MTF pays ii for the first request to each xix_i and 1 for the repeats, about n2n^2 in total. Repeating such blocks (each time in the reverse of FC's current order) gives a ratio of order nn.

python · try it yourself
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 rr means a competitive ratio of at least r/2r/2; both columns grow linearly in nn.

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 1.751.75-competitive against an oblivious adversary.

The best known randomized algorithm is COMB (Albers, von Stengel and Werchner, 1995), 1.61.6-competitive, and no randomized algorithm beats 1.51.5 against an oblivious adversary (Teia, 1993); the exact randomized ratio is open. Deterministically, nothing beats 2−2n+12 - \frac{2}{n+1} (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).

python · try it yourself
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 Φ\Phi?

  1. MTF's total cost so far
  2. The number of pairs of items whose relative order differs between MTF's list and the competitor's list
  3. The position of the requested item
  4. The number of paid exchanges

Item xx 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?

  1. 99
  2. 5=2⋅3−15 = 2 \cdot 3 - 1
  3. 1717
  4. 33

Why is transpose not competitive?

  1. It uses paid exchanges
  2. Alternating requests to its last two items keep both at the back forever, costing about nn per request while OPT pays about 2
  3. It is randomized
  4. It never moves items

What are the known bounds for randomized list update against an oblivious adversary?

  1. Exactly 2
  2. Upper bound 1.61.6 (COMB), lower bound 1.51.5; the exact value is open
  3. Upper bound 1.751.75, lower bound 1.751.75
  4. It equals HnH_n