LRU Cache Design Problem Statement
Design and implement a data structure for a Least Recently Used (LRU) cache that supports the following operations:
get(key)
- Retrieve the value associated with the specified key if it exists in the cache; otherwise, return -1.put(key, value)
- Insert or update the value associated with the specified key. If the cache has reached its capacity, evict the least recently used item before inserting the new item.
Input:
The first line of input contains two space-separated integers 'C' and 'Q', representing the capacity of the cache and the number of operations to perform, respectively.
Each of the next 'Q' lines contains an operation. If the operation starts with 0, it implies a 'get' operation, followed by the key. If it starts with 1, it implies a 'put' operation, followed by the key and value.
Output:
For each 'get' operation (i.e., when the operation starts with 0), print the value associated with the key if it exists; otherwise, print -1.
Example:
Sample Input 1:
3 11
1 1 1
1 2 2
1 3 3
1 4 5
0 3
0 1
0 4
1 2 3
0 1
0 3
0 2
Sample Output 1:
3
-1
5
-1
3
3
Constraints:
1 <= C <= 10^4
1 <= Q <= 10^5
1 <= key, value <= 10^9
- Time Limit: 1 second
Note:
No printing is needed from your implementation; just implement the function as described.

AnswerBot
4mo
Design and implement a Least Recently Used (LRU) cache data structure that supports get and put operations with a specified capacity.
Implement a doubly linked list to keep track of the order of keys b...read more
Help your peers!
Add answer anonymously...
Goldman Sachs Software Engineer interview questions & answers
A Software Engineer was asked 3mo agoQ. How do we make money?
A Software Engineer was asked Q. How do you create a BST from an incoming stream of nodes?
A Software Engineer was asked Q. Given an integer array nums, find a contiguous non-empty subarray within the arr...read more
Popular interview questions of Software Engineer
A Software Engineer was asked 3mo agoQ1. How do we make money?
A Software Engineer was asked Q2. How do you create a BST from an incoming stream of nodes?
A Software Engineer was asked Q3. Given an integer array nums, find a contiguous non-empty subarray within the arr...read more
>
Goldman Sachs Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app


Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+
Reviews
10L+
Interviews
4 Cr+
Salaries
1.5 Cr+
Users
Contribute to help millions
AmbitionBox Awards
Get AmbitionBox app

