Leetcode 146: LRU Cache

grid47
grid47
Exploring patterns and algorithms
Oct 23, 2024 7 min read

A cache where items are gently shifting in and out, with the most recently used glowing brightly.
Solution to LeetCode 146: LRU Cache Problem

Design and implement an LRU (Least Recently Used) cache. The cache should support two operations: get(key) and put(key, value). Both operations must run in O(1) time on average. If the cache exceeds its capacity, the least recently used key should be evicted.
Problem
Approach
Steps
Complexity
Input: The input consists of a series of operations on the LRUCache. The operations include initializing the cache with a given capacity and executing `get` and `put` commands.
Example: Input: ['LRUCache', 'put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Constraints:
• The number of operations will be at most 2 * 10^5.
• Capacity of the cache will be between 1 and 3000.
Output: The output should be a list of results corresponding to the `get` operation for each test case.
Example: Output: [null, null, null, 1, null, -1, null, -1, 3, 4]
Constraints:
• The output for each operation is either the return value of `get(key)` or null for `put(key, value)`.
Goal: Design a data structure that efficiently handles `get` and `put` operations with O(1) average time complexity.
Steps:
• Use a hash map to store the key-value pairs for O(1) lookups.
• Use a doubly linked list to maintain the order of use of keys, where the most recently used key is at the front and the least recently used is at the back.
• On `put`, add the key-value pair to the cache and move it to the front. If the cache exceeds capacity, evict the least recently used key from the back.
Goal: The implementation must ensure that both `get` and `put` operations run in O(1) average time.
Steps:
• Capacity is a positive integer and will not exceed 3000.
• The cache must efficiently handle up to 2 * 10^5 operations.
Assumptions:
• The cache will only contain integer keys and values.
• The input operations will be well-formed and within the constraints.
Input: Input: ['LRUCache', 'put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'] [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
Explanation: In this example, the cache is initialized with a capacity of 2. The operations are performed as described, with key-value pairs being added to the cache and the least recently used keys being evicted when necessary.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus