Tutorialspoint
Problem
Solution
Submissions

LFU Cache

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 20

Write a C program to implement a Least Frequently Used (LFU) cache data structure. The cache should support get and put operations in O(1) average time complexity. When the cache reaches its capacity, it should invalidate and remove the least frequently used key. If there are multiple keys with the same minimum frequency, remove the least recently used among them.

Example 1
  • Input: capacity = 2, operations = [put(1,1), put(2,2), get(1), put(3,3), get(2), get(3), get(1)]
  • Output: [null, null, 1, null, -1, 3, 1]
  • Explanation: put(1,1) and put(2,2) - cache is now {1:1, 2:2}. get(1) returns 1, frequency of key 1 increases. put(3,3) - capacity exceeded, remove key 2 (least frequent), cache is {1:1, 3:3}.
Example 2
  • Input: capacity = 1, operations = [put(2,1), get(2), put(3,2), get(2), get(3)]
  • Output: [null, 1, null, -1, 2]
  • Explanation: put(2,1) - cache is {2:1}. get(2) returns 1. put(3,2) - capacity exceeded, remove key 2, cache is {3:2}.
Constraints
  • 1 ≤ capacity ≤ 10^4
  • 0 ≤ key ≤ 10^5
  • 0 ≤ value ≤ 10^9
  • 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)
Data StructureEYD. E. Shaw
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 hash table to store key-value pairs and frequency information
  • Use a hash table to group keys by their frequency
  • Maintain a minimum frequency counter to track the least frequent keys
  • Use doubly linked lists to maintain insertion order within same frequency
  • Update frequency and relink nodes when accessing or inserting elements

Steps to solve by this approach:

 Step 1: Create data structures - hash table for key-node mapping and frequency-list mapping.

 Step 2: Implement doubly linked lists for each frequency to maintain insertion order.
 Step 3: For get operation, find the node, update its frequency, and move to appropriate list.
 Step 4: For put operation, check if key exists and update, or create new node.
 Step 5: When at capacity, remove the least frequently used (and least recently used among ties).
 Step 6: Update minimum frequency counter when adding/removing nodes.
 Step 7: Maintain proper linking of nodes in doubly linked lists for O(1) operations.

Submitted Code :