LRU Cache Audit

medium linked-list hashing simulation 2000 ms · 256 MB

LRU Cache Audit

An edge node of a content delivery network keeps at most C objects in memory. Before rolling out a new capacity setting, the operations team wants to replay a recorded request trace and audit what the cache would have done.

The cache starts empty and processes the n GET requests of the trace in order. Each request names an object by its key:

  • If the key is in the cache, the request is a hit, and the object becomes the most recently used one.
  • Otherwise the request is a miss: the object is fetched from the origin and inserted as the most recently used one. If the cache now holds more than C objects, the least recently used object (the one whose latest request is the oldest) is evicted.

An evicted object can be requested again later; that request is a miss and inserts it anew.

Report the number of hits, the number of misses, and the keys of the evicted objects in the order they were evicted.

Input

The first line contains two integers n and C (1 ≤ n ≤ 10^6, 1 ≤ C ≤ 10^6): the number of requests and the cache capacity.

Each of the next n lines contains one key: a string of 1 to 8 characters, each a lowercase English letter or a digit. Keys are compared as strings, so 007 and 7 are different keys.

Output

On the first line print two integers: the number of hits and the number of misses.

On the second line print E, the number of evictions.

On the third line print the E evicted keys separated by spaces, in the order they were evicted. If E = 0, this line is empty.

Notes

In the first example the capacity is 2. The requests img1, css, img1 are two misses and a hit, after which img1 is more recent than css. The miss on js overflows the cache and evicts css. The following request for css is a miss that evicts img1, and the final js is a hit.

In the second example the cache is large enough that nothing is ever evicted.

Example 1

Input

6 2
img1
css
img1
js
css
js

Output

2 4
2
css img1

Example 2

Input

5 3
a
b
a
c
b

Output

2 3
0

Hints · reveal one at a time if you're stuck

Hint 1

Eviction always removes the least recently used object, and every hit must move an object to the most recent position. Which structure lets you move an item to the front and remove the item at the back in constant time?

Hint 2

A list ordered by recency gives you the eviction order, but scanning it to find a key is far too slow. What can you pair with the list so that you jump straight to any key's position in it?

Hint 3

Use a doubly linked list of cached keys, with a hash map from each key to its node. On a hit, unlink and reinsert the node at the front. On a miss that overflows the capacity, remove the tail, record its key as evicted, and remove it from the map.

report an issue Prefer your own editor? sooks prep 38 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.