LRU Cache

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

  1. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
  2. set(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least recently used item before inserting the new item.
The LRU Cache will be initialized with an integer corresponding to its capacity. Capacity indicates the maximum number of unique keys it can hold at a time.

Definition of “least recently used” : An access to an item is defined as a get or a set operation of the item. “Least recently used” item is the one with the oldest access time.

NOTE: If you are using any global variables, make sure to clear them in the constructor. 
Example :

Input : 
         capacity = 2
         set(1, 10)
         set(5, 12)
         get(5)        returns 12
         get(1)        returns 10
         get(10)       returns -1
         set(6, 14)    this pushes out key = 5 as LRU is full. 
         get(5)        returns -1 
Solution:

Time: O(1)
Space: O(n)

public class Solution {
    private LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
    private int cap = 0;
    
    public Solution(int capacity) {
        this.cap = capacity;
    }
    
    public int get(int key) {
        if (map.containsKey(key)) {
            int val = map.get(key);
            map.remove(key);
            map.put(key, val);
            return val;
        }
        return -1;
    }
    
    public void set(int key, int value) {
        if (map.size() >= this.cap && !map.containsKey(key)) {
            Map.Entry<Integer, Integer> entry = map.entrySet().iterator().next();
            map.remove(entry.getKey());
        }
        if (map.containsKey(key)) {
            map.remove(key);
        }
        map.put(key, value);
    }
}