Logo

dev-resources.site

for different kinds of informations.

Implement LRU Cache

Published at
12/4/2024
Categories
machine
coding
interview
system
Author
prashantrmishra
Categories
4 categories in total
machine
open
coding
open
interview
open
system
open
Author
15 person written this
prashantrmishra
open
Implement LRU Cache

Problem

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

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
Enter fullscreen mode Exit fullscreen mode

With using doubly LinkedList

O(1) for read and write

class LRUCache {
    DLinkedList head = null;
    DLinkedList tail = null;
    int capacity = 0;
    Map<Integer, DLinkedList> map = new HashMap<>();

    public LRUCache(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        DLinkedList node = map.getOrDefault(key, null);
        if (node == null)
            return -1;

        // Move the accessed node to the end (most recently used)
        remove(node);
        addToTail(node);
        return node.value;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            // Key exists; update value and move to the end
            DLinkedList node = map.get(key);
            node.value = value;
            remove(node);
            addToTail(node);
        } else {
            // Key doesn't exist; create a new node
            if (map.size() == capacity) {
                // Evict the least recently used (head node)
                map.remove(head.key);
                remove(head);
            }
            DLinkedList newNode = new DLinkedList(key, value);
            addToTail(newNode);
            map.put(key, newNode);
        }
    }

    private void remove(DLinkedList node) {
        if (node.prev != null) {
            node.prev.next = node.next;
        } else {
            // Node is head
            head = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        } else {
            // Node is tail
            tail = node.prev;
        }
        node.prev = null;
        node.next = null;
    }

    private void addToTail(DLinkedList node) {
        if (tail == null) {
            // List is empty
            head = tail = node;
        } else {
            // Add to end of the list
            tail.next = node;
            node.prev = tail;
            tail = node;
        }
    }

    public void traverse() {
        DLinkedList n = head;
        while (n != null) {
            System.out.print(n.prev + "<--[" + n.key + "," + n.value + "]-->" + n.next);
            n = n.next;
        }
        System.out.println();
    }
}

class DLinkedList {
    DLinkedList prev;
    DLinkedList next;
    int key;
    int value;

    public DLinkedList(int k, int v) {
        this.key = k;
        this.value = v;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
Enter fullscreen mode Exit fullscreen mode
system Article's
30 articles in total
Favicon
You Won’t Believe What Happens When You Click ‘Upload’
Favicon
Understanding Commodore Operating Systems
Favicon
Implement LRU Cache
Favicon
Conway’s Law - How Organizational Communication Shapes System Design
Favicon
kafka deep dive
Favicon
Please Install It for Me
Favicon
Reconstructing Shopping Bill Dataset from OCR Data using Bash
Favicon
5 text processing tools `grep, sed, awk, cut, and tr` to score some marks in System Commands OPPE
Favicon
10 Linux commands to score 25 marks in System Commands OPPE
Favicon
AWS Systems Manager Session Manager Hands-on: Securely Manage Your EC2 Instances from Anywhere
Favicon
LED display principle and system composition
Favicon
The Power of System Integration Testing: 5 Transformative Benefits
Favicon
Unveiling the Crucial Importance of System Integration Testing
Favicon
System Integration Testing Guide: All You Need To Know
Favicon
6 Features of Invoicing Software That Simplify Your Workday in 2024
Favicon
Exploring System Integration Testing Techniques: A Comprehensive Guide
Favicon
A Comprehensive Guide to Multi-Tenancy Architecture
Favicon
Benefits of the Oracle Warehouse Management System
Favicon
array, dictionary, for and while loops to score 25 marks in System Commands OPPE
Favicon
Zeep Service -Your Travel Partner(Low-Level Design)
Favicon
5 Mistakes to Avoid While Going for System Integration Testing
Favicon
Reasons to Go for System Integration Testing in Software Testing
Favicon
Benefits of System Integration Testing Tools in 2024
Favicon
5 Tips to Choose the Best System Integration Testing Tool
Favicon
The Invaluable Advantages of System Integration Testing (SIT)
Favicon
RDBMS: Key Concepts and Principles of Relational Database Management System
Favicon
Mistakes to Steer Clear of During System Integration Testing
Favicon
The Vital Importance of System Integration Testing (SIT)
Favicon
Challenges in System Integration Testing and Opkey’s Solutions
Favicon
Everything You Should Know About Integrated System Testing

Featured ones: