Least Recently Used Cache - Amazon Top Interview Questions
Problem Statement :
Implement a least recently used cache with the following methods: LRUCache(int capacity) constructs a new instance of a LRU cache with the given capacity. get(int key) retrieves the value associated with the key key. If it does not exist, return -1. As a side effect, this key now becomes the most recently used key. set(int key, int val) updates the key key with value val. If updating this key-value pair exceeds capacity, then evicts the least recently used key-value pair. Each method should be done in \mathcal{O}(1)O(1) time. Constraints n ≤ 100,000 where n is the number of calls to get and set. Example 1 Input methods = ["constructor", "set", "get", "set", "set", "set", "get", "get"] arguments = [[3], [1, 10], [1], [2, 20], [3, 30], [4, 40], [1], [4]]` Output [None, None, 10, None, None, None, -1, 40] Explanation We create an LRUCache of capacity 3. Set key of 1 to value 10. Size of cache is now 1 We get 1 which has value of 10 Set key of 2 to value 20. Size of cache is now 2 Set key of 3 to value 30. Size of cache is now 3 Set key of 4 to value 40. Size exceeds capacity, so now we evict the least recently used key which is 1. We get 1 which has been evicted so we return -1 We get 4 which has value of 40
Solution :
Solution in C++ :
class LRUCache {
public:
LRUCache(int capacity) : cap(capacity) {
}
int get(int key) {
auto it = m.find(key);
if (it == m.end()) return -1;
auto lit = it->second;
int val = lit->second;
lst.erase(lit);
lst.push_front({key, val});
it->second = lst.begin();
return val;
}
void set(int key, int val) {
auto it = m.find(key);
if (it == m.end()) {
lst.push_front({key, val});
m.insert({key, lst.begin()});
} else {
auto lit = it->second;
lst.erase(lit);
lst.push_front({key, val});
it->second = lst.begin();
}
if (lst.size() > cap) {
auto p = lst.back();
m.erase(p.first);
lst.pop_back();
}
}
private:
int cap;
list<pair<int, int>> lst;
unordered_map<int, list<pair<int, int>>::iterator> m;
};
Solution in Python :
class DLLNode:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
self.prev = None
class DLL:
def __init__(self):
"""
initialize Doubly Linked List with 2 dummy nodes to
get first and last nodes in O(1) time because our operations
require us to either push to the front or pop from the end.
"""
self.head = DLLNode(0, 0)
self.tail = DLLNode(0, 0)
self.head.next, self.tail.prev = self.tail, self.head
self.size = 0
def delete(self, node):
"""
Delete a DLL node, given its pointer. we just update the
2 pointers that point to this node and we're done
"""
node.next.prev, node.prev.next = node.prev, node.next
self.size -= 1
def push_front(self, node):
"""
since we already have the pointer to the head of DLL, we just push this
node to the next of the head
"""
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
self.size += 1
def get_last(self):
return self.tail.prev
class LRUCache:
def __init__(self, capacity):
self.dll = DLL()
self.mapping = {}
self.capacity = capacity
def get(self, key):
"""
If the key is not present in mapping, we simply return -1.
Else we get the pointer to that node in the DLL and move the node
to the front and return its value
"""
if key not in self.mapping:
return -1
node = self.mapping[key]
# now move this node to the front of the array
self.dll.delete(node)
self.dll.push_front(node)
return node.val
def set(self, key, val):
"""
If key already has a value set, we get the DLL node and delete it.
We don't remove from the mapping since we will overwrite it anyway.
then we create a new node and insert to the front of the DLL and update
the mapping with this new node.
If the size is more than the capacity, we get the last element and pop it
"""
if key in self.mapping:
node = self.mapping[key]
self.dll.delete(node)
# add a new entry to the front
node = DLLNode(key, val)
self.dll.push_front(node)
self.mapping[key] = node
# if the size is more than the capacity, pop last
if len(self.mapping) > self.capacity:
last_node = self.dll.get_last()
self.dll.delete(last_node)
del self.mapping[last_node.key]
View More Similar Problems
Self-Driving Bus
Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever
View Solution →Unique Colors
You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti
View Solution →Fibonacci Numbers Tree
Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T
View Solution →Pair Sums
Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v
View Solution →Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →Ticket to Ride
Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o
View Solution →