Design and implement a data structure for Least Recently Used (LRU) cache by supporting set() and get() operations with O(1) complexity.

Least Recently Used (LRU) Cache?Its a caching mechanism where we evicts least recently used items from the cache to accommodate new entries at top. So in that case in cache we maintain only the recently used data and least used entries will be evicted once we need to set new value in cache. How to implement simple LRU Cache?We can implement by using multiple data structure like stack, Queue, LinkedList etc., Now in this tutorial lets see how to implement by using Doubly LinkedList and map to hold the LinkedList nodes which makes O(1) complexity for our read / get() operation.

Steps:

NodeLRU class which holds the data, next and previous node values.

In LRUCache setting cache size as 5 to make it simple

set() method will check already value present in map or not. If its present remove the existing value from map and LinkedList and add the new value in LinkedList and map.

get() method will fetch node if present in map and return the values or else return -1 if not present.

Once we get the value the node will be shifted to the head of LinkedList to make it as recently used.

By this way we can implement the LRU cache with simple logic by using LinkedList and map. Lets see the java implementation for the same