Taro Logo

LRU Cache

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+95
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
11.5K views
Topics:
Linked Lists

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  • LRUCache(int capacity) Initialize the LRU cache with positive size capacity.
  • int get(int key) Return the value of the key if the key exists, otherwise return -1.
  • 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 from this operation, evict the least recently used key.

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

Example 1:

Input
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, null, -1, 3, 4]

Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1);    // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2);    // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1);    // return -1 (not found)
lRUCache.get(3);    // return 3
lRUCache.get(4);    // return 4

Constraints:

  • 1 <= capacity <= 3000
  • 0 <= key <= 104
  • 0 <= value <= 105
  • At most 2 * 105 calls will be made to get and put.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What data types should we expect for the keys and values, and are they guaranteed to fit within standard memory limits?
  2. What should the `get` operation return if the requested key does not exist in the cache?
  3. How should the cache behave if `put` is called with a key that already exists (does it update the value and mark it as most recently used, or is it considered a duplicate addition)?
  4. Is the capacity of the cache guaranteed to be a positive integer greater than zero?
  5. Are there any concurrency requirements (thread-safety), or can we assume a single-threaded environment for this implementation?

Brute Force Solution

Approach

Imagine you have a small desk with a strict limit on how many items can fit on it at one time. The brute force strategy involves searching through your entire collection of items from scratch every time someone asks for something or hands you a new piece of work.

Here's how the algorithm would work step-by-step:

  1. Whenever someone asks for a specific item, look through your entire collection one by one until you find the right one.
  2. If the item is not currently on your desk, search through all your stored boxes everywhere in the room to find it.
  3. Once you find the item, bring it to your desk so the person can use it.
  4. If your desk is completely full when you need to bring a new item onto it, review all the items currently on the desk to figure out which one has been sitting there the longest without being touched.
  5. Take that oldest item off the desk and put it away in a storage box to make space for the new item.
  6. Place the new item onto the desk and repeat this entire search and cleanup process for every single request that comes in.

Code Implementation

class LRUCache:
    def __init__(self, capacity: int):
        self.cache_capacity = capacity
        self.desk_collection = []
        self.storage_room = {}

    def get(self, key: int) -> int:
        # We search the desk collection linearly to find and refresh the accessed item
        for item_index, item_pair in enumerate(self.desk_collection):
            if item_pair[0] == key:
                found_pair = self.desk_collection.pop(item_index)
                self.desk_collection.append(found_pair)
                return found_pair[1]

        if key in self.storage_room:
            retrieved_value = self.storage_room[key]
            if len(self.desk_collection) >= self.cache_capacity:
                oldest_item = self.desk_collection.pop(0)
                self.storage_room[oldest_item[0]] = oldest_item[1]
            
            self.desk_collection.append([key, retrieved_value])
            del self.storage_room[key]
            return retrieved_value

        return -1

    def put(self, key: int, value: int) -> None:
        # Existing keys must be updated in place and moved to the most recent position
        for item_index, item_pair in enumerate(self.desk_collection):
            if item_pair[0] == key:
                self.desk_collection.pop(item_index)
                self.desk_collection.append([key, value])
                return

        if key in self.storage_room:
            self.storage_room[key] = value
            self.get(key)
            return

        if len(self.desk_collection) >= self.cache_capacity:
            oldest_item = self.desk_collection.pop(0)
            self.storage_room[oldest_item[0]] = oldest_item[1]

        self.desk_collection.append([key, value])

Big(O) Analysis

Time Complexity
O(n) – To service a request, we must search sequentially through a collection of n items on the desk, checking each one individually one by one. If the item is missing from the desk, we must also search through all stored boxes everywhere in the room, which scales linearly with the total number of items n. Finding, updating, or evicting the oldest item requires scanning through all n elements of the current collection for every single operation that comes in. This exhaustive sequential search results in approximately n operations per request, which simplifies to a linear time complexity of O(n).
Space Complexity
O(capacity) – The auxiliary space is driven by the desk itself, which acts as a collection container holding a maximum of capacity items at any given time. As the capacity limit defines the maximum number of items that can be stored simultaneously on the desk and in the storage boxes, the extra memory used scales directly with this limit rather than the total number of historical requests. Therefore, the total auxiliary memory required simplifies to Big O of capacity, where capacity represents the maximum allowed items on the desk.

Optimal Solution

Approach

To build a lightning-fast memory storage system that forgets its oldest items when it gets too full, we combine a quick-reference directory with a flexible chain of items. This clever combination lets us find, add, and remove items almost instantly, no matter how many things we are storing.

Here's how the algorithm would work step-by-step:

  1. Imagine a row of items where the most recently used item is always kept at the very front, and the oldest, least used item naturally drifts toward the very back.
  2. Keep a separate master index or phone book that points directly to the exact location of every single item, allowing you to instantly jump to it without searching through the entire collection.
  3. Whenever you ask for an item, look it up instantly using the master index, pull it out from its current spot, and move it straight to the very front of the line to show it was just used.
  4. Whenever you add a new item, check if you already have it; if so, update its value and move it to the front just like before.
  5. If you are adding a brand-new item and the storage space is completely full, gently take the item sitting at the very back of the line and throw it away to make room.
  6. Place your brand-new item at the very front of the line and update your master index so you can find it easily next time.

Code Implementation

class DoublyLinkedListNode:
    def __init__(self, cache_key=0, cache_value=0):
        self.cache_key = cache_key
        self.cache_value = cache_value
        self.previous_node = None
        self.next_node = None


class LRUCache:
    def __init__(self, maximum_capacity: int):
        self.maximum_capacity = maximum_capacity
        self.cache_directory = {}
        self.head_sentinel = DoublyLinkedListNode()
        self.tail_sentinel = DoublyLinkedListNode()
        self.head_sentinel.next_node = self.tail_sentinel
        self.tail_sentinel.previous_node = self.head_sentinel

    def _remove_node(self, target_node):
        previous_item = target_node.previous_node
        following_item = target_node.next_node
        previous_item.next_node = following_item
        following_item.previous_node = previous_item

    def _add_node_to_front(self, target_node):
        following_item = self.head_sentinel.next_node
        self.head_sentinel.next_node = target_node
        target_node.previous_node = self.head_sentinel
        target_node.next_node = following_item
        following_item.previous_node = target_node

    def _move_node_to_front(self, target_node):
        self._remove_node(target_node)
        self._add_node_to_front(target_node)

    def _pop_tail_node(self):
        oldest_node = self.tail_sentinel.previous_node
        self._remove_node(oldest_node)
        return oldest_node

    def get(self, cache_key: int) -> int:
        # Look up instantly in our master index to find the exact item location.
        if cache_key not in self.cache_directory:
            return -1

        target_node = self.cache_directory[cache_key]
        self._move_node_to_front(target_node)
        return target_node.cache_value

    def put(self, cache_key: int, cache_value: int) -> void:
        # Update existing items and refresh their position to the front of the line.
        if cache_key in self.cache_directory:
            target_node = self.cache_directory[cache_key]
            target_node.cache_value = cache_value
            self._move_node_to_front(target_node)
            return

        # Evict the oldest item at the back when capacity is fully exhausted.
        if len(self.cache_directory) >= self.maximum_capacity:
            oldest_node = self._pop_tail_node()
            del self.cache_directory[oldest_node.cache_key]

        new_node = DoublyLinkedListNode(cache_key, cache_value)
        self._add_node_to_front(new_node)
        self.cache_directory[cache_key] = new_node

Big(O) Analysis

Time Complexity
O(1) – Both the get and put operations rely on a hash map for instant lookups and a doubly linked list for immediate node insertions and deletions. Because these underlying data structures perform pointer manipulations and hash lookups in constant time, the cost does not depend on the total capacity or number of items stored. Consequently, every operation executes in constant time, which simplifies to O(1).
Space Complexity
O(capacity) – The auxiliary space is driven by two main data structures: a hash map (the master index) and a doubly linked list (the row of items). Both structures store at most a number of elements equal to the cache capacity, denoted as N. Each node in the list and each entry in the map consume a constant amount of memory per item. Therefore, as the capacity N increases, the extra memory required grows proportionally, resulting in a linear space complexity of O(N).

Edge Cases

Cache capacity is set to 1
How to Handle:
The least recently used item must be evicted on every subsequent insertion after the first.
Accessing or updating an existing key
How to Handle:
The existing node is moved to the most recently used position without changing the cache capacity.
Inserting a key that already exists with a new value
How to Handle:
Update the value and promote the node to the head of the doubly linked list.
Cache reaches full capacity and a new unique key is inserted
How to Handle:
Remove the tail node from the linked list and delete it from the hash map before adding the new item.
Retrieving a key that does not exist in the cache
How to Handle:
Return negative one or the standard language-specific absence indicator immediately.
Zero or negative values for capacity
How to Handle:
Initialize a conditional check to handle invalid capacities gracefully by throwing an error or ignoring operations.
Keys and values include extreme boundary integers like negative numbers or zero
How to Handle:
The hash map uses exact key matching and the linked list stores generic pointers, making key-value identity agnostic to number signs.
High frequency of continuous gets on the same key
How to Handle:
Repeatedly moving the same node to the front remains an O(1) operation due to direct pointer manipulation.
0/75 completed