Mid From PDF Power Questions High-Impact Interview Questions

LRU Cache?

Removes least recently used entries when full.

public class LruCache<TKey,TValue>
{
private readonly int capacity;
private readonly Dictionary<TKey, LinkedListNode<(TKey,TValue)>> cache = new();
private readonly LinkedList<(TKey,TValue)> list = new();
public LruCache(int capacity) => this.capacity = capacity;
public TValue Get(TKey key)
{
if (!cache.ContainsKey(key)) return default;
var node = cache[key];
list.Remove(node);
list.AddFirst(node);
return node.Value.Item2;
}
public void Put(TKey key, TValue value)
{
if (cache.ContainsKey(key))
list.Remove(cache[key]);
if (cache.Count == capacity)
{
var last = list.Last;

cache.Remove(last.Value.Item1);

list.RemoveLast();
}
var newNode = new LinkedListNode<(TKey,TValue)>((key,value));
list.AddFirst(newNode);
cache[key] = newNode;
}
}

More from Career Preparation

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details