• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
August 21, 2024 |260 Views

SDE Sheet - LRU Cache

Description
Discussion

This video is part of the Stack and Queue section under GFG SDE Sheet.

Design a data structure that works like a LRU Cache. Here cap denotes the capacity of the cache and Q denotes the number of queries. Query can be of two types:

  1. SET x y: sets the value of the key x with value y
  2. GET x: gets the key of x if present else returns -1.


The LRUCache class has two methods get() and set() which are defined as follows.

  1. get(key): returns the value of the key if it already exists in the cache otherwise returns -1.
  2. set(key, value): if the key is already present, update its value. If not present, add the key-value pair to the cache. If the cache reaches its capacity it should invalidate the least recently used item before inserting the new item.
  3. In the constructor of the class the capacity of the cache should be initialized.

 

Example 1:

Input: cap = 2 Q = 2 Queries = SET 1 2 GET 1 Output: 2 Explanation: Cache Size = 2 SET 1 2 GET 1 SET 1 2 : 1 -> 2 GET 1 : Print the value corresponding to Key 1, ie 2.

Do check out:-
Problem: https://www.geeksforgeeks.org/problems/lru-cache/1
SDE Sheet Link: https://www.geeksforgeeks.org/sde-sheet-a-complete-guide-for-sde-preparation/
Article Link: https://www.geeksforgeeks.org/lru-cache-implementation/