Tutorialspoint
Problem
Solution
Submissions

LRU Cache

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to implement an LRU (Least Recently Used) Cache. The cache should support get and put operations. When the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item. Both get and put operations should run in O(1) average time complexity.

Example 1
  • Input: capacity = 2, operations = [put(1,1), put(2,2), get(1), put(3,3), get(2), put(4,4), get(1), get(3), get(4)]
  • Output: [null, null, 1, null, -1, null, -1, 3, 4]
  • Explanation: put(1,1) - Cache: {1=1}. put(2,2) - Cache: {1=1, 2=2}. get(1) - Returns 1, Cache: {2=2, 1=1} (1 moved to end). put(3,3) - Capacity full, remove LRU(2), Cache: {1=1, 3=3}. get(2) - Returns -1 (not found).
Example 2
  • Input: capacity = 1, operations = [put(2,1), get(2), put(3,2), get(2)]
  • Output: [null, 1, null, -1]
  • Explanation: put(2,1) - Cache: {2=1}. get(2) - Returns 1, Cache: {2=1}. put(3,2) - Capacity full, remove LRU(2), Cache: {3=2}. get(2) - Returns -1 (not found).
Constraints
  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key ≤ 10^4
  • 0 ≤ value ≤ 10^5
  • At most 2 * 10^5 calls will be made to get and put
  • Time Complexity: O(1) for both get and put operations
  • Space Complexity: O(capacity)
Binary TreeAccentureShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a combination of doubly linked list and hash table
  • Hash table provides O(1) access to cache nodes
  • Doubly linked list maintains the order of usage
  • Most recently used items are at the tail of the list
  • Least recently used items are at the head of the list
  • When capacity is full, remove the head node before adding new node

Steps to solve by this approach:

 Step 1: Create a doubly linked list with dummy head and tail nodes for O(1) insertion/deletion.
 Step 2: Implement a hash table using chaining to provide O(1) access to cache nodes.
 Step 3: For get operation, find the node in hash table and move it to tail (most recently used).
 Step 4: For put operation, check if key exists and update value or create new node.
 Step 5: If cache is at capacity during insertion, remove the least recently used node (head).
 Step 6: Always add new or updated nodes to the tail to maintain LRU order.
 Step 7: Use hash table for O(1) lookups and doubly linked list for O(1) order maintenance.

Submitted Code :