LRU Cache using Doubly Linked List

Advantage of Using LRU Cache using Doubly Linked List Over List:


  • If we use list, then we have to overwrite the elements in the lis, where as in doubly linked list we have to just swap the pointers.
  • The cost of get and set operation is O(1).

package com.sudharsan.examples;

import java.util.HashMap;
import java.util.Map;

class Cache {
    int key;
    int value;
   
    Cache prev;
    Cache next;
   
    Cache(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

public class Solution {
   
    final int capacity;
    final Map<Integer, Cache> map = new HashMap<>();
    Cache head = null, tail = null;
   
    public Solution(int capacity) {
        this.capacity = capacity;  
    }
   
    public int get(int key) {
        if (map.containsKey(key)) {
            Cache cache = map.get(key);
            remove(cache);
            setHead(cache);
            return cache.value;
        }
        return -1;
    }
   
    public void remove(Cache cache) {
        if (cache.prev != null) {
            cache.prev.next = cache.next;
        } else {
            head = cache.next;
        }
       
        if (cache.next != null) {
            cache.next.prev = cache.prev;
        } else {
            tail = cache.prev;
        }
    }
   
    public void setHead(Cache cache) {
        cache.next = head;
        cache.prev = null;
       
        if (head != null) {
            head.prev = cache;
        }
       
        head = cache;
       
        if (tail == null) {
            tail = head;
        }
    }
   
    public void set(int key, int value) {
        if (map.containsKey(key)) {
            Cache cache = map.get(key);
            cache.value = value;
           
            remove(cache);
            setHead(cache);
        } else {
            Cache cache = new Cache(key, value);
            if (map.size() >= capacity) {
                map.remove(tail.key);
               
                remove(tail);
             
            }
             setHead(cache);
             map.put(key, cache);
        }
    }
}

Comments

Popular posts from this blog

Tiny URL Converter

Blocking Queue