[LeetCode 146] LRU Cache

Question

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: `get` and `set`.

`get(key)` - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
`set(key, value)` - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Stats

 Adjusted Difficulty 4 Time to use Very difficult

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a difficult question, I can’t write the solution easily even after a month.

Solution

The solution is to use a Doubly-linked-list and a HashMap. Doing this allows O(1) search, remove and insert. A very nice and sophisticated data structure example, and very high frequency in interviews.

2 important things to note while coding:

1. We need 2 helper methods: removeNode() and setNodeAsHead().

Because we reuse both methods for get() and set() methods.

2. Initialization of LRU

We need 5 variables: capacity, current size(optional but good to have), hashmap, head, tail.

3. Initialization of DoubleLinkedListNode

This is easy, but do not forget about both key and value variable. We must use DoubleLinkedListNode.key when we want to delete tail.

Code

Updated on July 1st, 2014.

This question tests your ability to write some DS by yourself, eg. DoubleLinkedList.

``````public class LRUCache {

int size;
int capacity;

public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
tail = null;
map = new HashMap<Integer, DoubleLinkedList>();
}

public void remove(DoubleLinkedList node) {
if (node == head && node == tail) {
tail = null;
} else if (node == head) {
} else if (node == tail) {
tail.prev.next = null;
tail = tail.prev;
} else {
node.prev.next = node.next;
node.next.prev = node.prev;
}
node.prev = null;
node.next = null;
}

node.prev = null;
if (head != null) {
}

if (tail == null) {
tail = node;
}
}

public int get(int key) {
if (!map.containsKey(key)) {
return -1;
} else {
// if key is found
DoubleLinkedList target = map.get(key);
remove(target);
}
}

public void set(int key, int value) {
if (this.get(key) != -1) {
// key exist before, just replace the old value
DoubleLinkedList old = map.get(key);
old.val = value;
} else {
// this is a new key-value pair, insert it
if (size == capacity) {
// delete tail
map.remove(tail.key);
remove(tail);
} else {
size++;
}
}
}