Move-to-front
A self-organizing list: each requested item moves to the front, so popular items stay near it; its cost is at most 4 times the best offline method's.
In a linked list, finding the k-th item takes k steps. If some items are requested more often, they should sit
near the front. But we do not know which ones in advance; the algorithm has to decide online.
- Time:
O(position) per request - Space:
O(1) extra - CLRS, chapter 27
The list starts as 1 2 3 4 5 and the requests keep coming back to 4 and 5; after the first time they sit at the front and are cheap.
def move_to_front(L, R):lst = list(L[0])cells = [lst] # for the picture: the list as one table rowcost = 0for x in R[0]:i = 0while i < len(lst) and lst[i] != x:i = i + 1if i == len(lst):lst.append(x)cost = cost + i + 1lst.pop(i)lst.insert(0, x)return cost
Start
The table is still empty.
Local variables
Orange = changed in this step
L list
R list
Call stack
- move_to_front()line 1
Explanation
The idea
In a linked list, finding the k-th item takes k steps. If some items are requested more often, they should sit
near the front. But we do not know which ones in advance; the algorithm has to decide online.
Move-to-front is the simplest rule: each requested item moves to the front of the list. Other rules:
- transpose: the requested item swaps only with the item in front of it;
- frequency count: the list stays sorted by how often each item was requested.
Competitive analysis
Sleator and Tarjan showed that on any request sequence, move-to-front costs at most 4 times what the best offline method costs, one that knows all requests in advance (counting swaps). Transpose has no such guarantee.
The input
L is the starting list and R the requests. A request that is not in the list is added at its end.