Modified LRU Cache for Dasher Delivery Assignments
Implement a fixed-capacity cache that stores the most recent delivery assigned to each dasher. The cache keeps dashers based only on how recently their entries were added or updated.
Cache Behavior
- Each cache entry maps one
dasherId to one deliveryId.
- Calling
put makes the dasher the most recently updated entry.
- Calling
get does not change the entry's update order.
- If an insertion causes the cache size to exceed its capacity, remove the dasher whose entry was updated least recently.
Methods
Initialize Cache
void init(int capacity)
Initialize an empty cache that can store information for at most capacity dashers.
Add or Update Delivery
void put(int dasherId, int deliveryId)
- If
dasherId is not in the cache, add it with the given deliveryId.
- If
dasherId is already in the cache, replace its current delivery with deliveryId.
- The inserted or updated dasher becomes the most recently updated entry.
- If the cache exceeds its capacity, remove the least recently updated entry.
Get Most Recent Delivery
int get(int dasherId)
- Return the stored
deliveryId for dasherId.
- Return
-1 if dasherId is not in the cache.
- This operation does not change the update order of any cache entry.
Important Difference from an LRU Cache
In a standard least-recently-used cache, both put and get usually make an entry the most recently used. In this cache, only put changes the entry order.
Constraints
1 ≤ capacity ≤ 100,000
1 ≤ dasherId ≤ 1,000,000,000
1 ≤ deliveryId ≤ 1,000,000,000
init is called exactly once before any call to put or get.
Examples
Example 1: Reading an Entry Does Not Protect It from Eviction
Method calls:
init(capacity = 2)
put(dasherId = 11, deliveryId = 701)
put(dasherId = 22, deliveryId = 702)
get(dasherId = 11) returns 701
put(dasherId = 33, deliveryId = 703)
get(dasherId = 11) returns -1
get(dasherId = 22) returns 702
Dasher 11 is removed because its entry was updated before dasher 22. Calling get for dasher 11 did not make it more recent.
Example 2: Updating an Existing Dasher Changes Its Order
Method calls:
init(capacity = 2)
put(dasherId = 40, deliveryId = 810)
put(dasherId = 50, deliveryId = 820)
put(dasherId = 40, deliveryId = 830)
put(dasherId = 60, deliveryId = 840)
get(dasherId = 40) returns 830
get(dasherId = 50) returns -1
get(dasherId = 60) returns 840
Updating dasher 40 makes it the most recently updated entry. Therefore, dasher 50 is removed when dasher 60 is added.
Example 3: Capacity of One
Method calls:
init(capacity = 1)
put(dasherId = 7, deliveryId = 901)
get(dasherId = 7) returns 901
put(dasherId = 8, deliveryId = 902)
get(dasherId = 7) returns -1
get(dasherId = 8) returns 902