Header Ad

Leetcode LRU Cache problem solution

In this Leetcode LRU Cache problem solution, we need to Design, a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  1. LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  2. int get(int key) Return the value of the key if the key exists, otherwise return -1.
  3. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity of this operation, evict the least recently used key.

The functions get and put must each run in O(1) average time complexity.

Leetcode LRU Cache problem solution


Problem solution in Python.

def __init__(self, capacity):
    self.dic = collections.OrderedDict()
    self.remain = capacity

def get(self, key):
    if key not in self.dic:
        return -1
    v = self.dic.pop(key) 
    self.dic[key] = v   # set key as the newest one
    return v

def set(self, key, value):
    if key in self.dic:    
        self.dic.pop(key)
    else:
        if self.remain > 0:
            self.remain -= 1  
        else:  # self.dic is full
            self.dic.popitem(last=False) 
    self.dic[key] = value



Problem solution in Java.

class LRUCache {
  Map<Integer, Integer> linkedMap;
  public LRUCache(final int capacity) {
    linkedMap = new LinkedHashMap<>(capacity, 1, true) {
      @Override
      public boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
        return capacity + 1 == size();
      }
    };
  }
  public int get(int key) {
    Integer v = linkedMap.get(key);
    return v == null ? -1 : v;
  }
  public void put(int key, int value) {
    linkedMap.put(key, value);
  }
}


Problem solution in C++.

list<int>dq;
    unordered_map<int, list<int>::iterator> mp;
    int a[3001];
    int c;
    LRUCache(int capacity) {
        for(int i=0;i<=3000;i++)
            a[i]=-1;
        c=capacity;
    }
    
    int get(int key) {
        if(mp.find(key)!=mp.end())
        {
            int val=a[key];
            dq.erase(mp[key]);
            dq.push_front(key);
            mp[key]=dq.begin();
        }
        return a[key];
        
    }
    
    void put(int key, int value) {
        if(mp.find(key)==mp.end())
        {
            if(dq.size()==c)
            {
                int last=dq.back();
                dq.pop_back();
                mp.erase(last);
                a[last]=-1;
            }
            
        }
        else
        {
            dq.erase(mp[key]);
            mp.erase(key);
        }
        
        dq.push_front(key);
        mp[key]=dq.begin();
        a[key]=value;
    }


Problem solution in C.

struct hash_map
{
  int key;
  int val;
  UT_hash_handle hh
};
typedef struct hash_map map;
map* cache = NULL;
map* cacheFind(int key);
void cacheCleanup();
void cachePrint();
void cacheInvalidate();
map* cacheAging(map* lastUsed);

int totalSize, used;

void lruCacheInit(int capacity)
{
  cache = NULL;
  totalSize = capacity;
  used = 0;
}

void lruCacheFree()
{
  cacheCleanup();
  used = 0;
}

int lruCacheGet(int key)
{
  map* s = cacheFind(key);
  if(s == NULL)    return -1;
  else
  {
    s = cacheAging(s);
    return s->val;
  }
}
    
void lruCacheSet(int key, int value)
{
  map* s;
  HASH_FIND_INT(cache, &key, s);
  if (s!=NULL)
  {
    s = cacheAging(s);
  }
  else
  {
    if(used == totalSize)
      cacheInvalidate();

    s = (map*)malloc(sizeof(map));
    s->key = key;
    HASH_ADD_INT(cache, key, s);
    used++;
  }
  s->val = value;
}

map* cacheAging(map* lastUsed)
{

  int key   = lastUsed->key;
  int value = lastUsed->val;

  HASH_DEL(cache, lastUsed);  
  free(lastUsed);

  map* s = (map*)malloc(sizeof(map));
  s->key = key;
  s->val = value;
  HASH_ADD_INT(cache, key, s);

  return s;
}

void cacheInvalidate()
{
  map* s = cache;
  HASH_DEL(cache,s);
  free(s);
  used--;
}

map* cacheFind(int key)
{
    map* s;
    HASH_FIND_INT(cache, &key, s);
    return s;
}

void cacheCleanup()
{
  map* cur, *tmp;
  HASH_ITER(hh, cache, cur, tmp)
  {
    HASH_DEL(cache, cur);
    free(cur);
  }
}

void cachePrint()
{
    map* s;
    for(s=cache; s != NULL; s=(map*)(s->hh.next))
      printf("key %d:  value %d\n", s->key, s->val);
}


Post a Comment

0 Comments