AlgoMaster Logo

LRU Cache

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Doubly Linked List with HashMap (Basic)

In this approach, we use a doubly linked list to maintain the order of use of the cache and a HashMap for quick access to elements. The doubly linked list maintains a list of nodes, each representing a key-value pair. The head of the list is the most recently used, and the tail is the least used.

Intuition:

  • Use a doubly linked list because it provides constant time access to update and remove nodes.
  • Use a HashMap to store references to the nodes of the linked list with the key-value pairs so that we can achieve O(1) time complexity for get and put operations.
  • When a key is accessed or added, move it to the head of the list. This denotes that it's the most recently used.
  • Upon hitting capacity, remove the node at the tail (least recently used).

Code:

2. Doubly Linked List with HashMap (Optimized)

The second approach involves the same data structures but focuses on optimizing memory usage and cleaning up code for efficiency.

Key Differences:

  • Consolidate the insert and remove methods for more concise code.
  • Ensure edge case handling for all corner scenarios in insert and removal of nodes.

Code: