Priority, Expiration, and LRU Eviction
Problem statement
A cache currently contains n items. Item i has key keys[i], priority priorities[i], expiration time expirations[i], and last-used time lastUsed[i].
Select the key of the one item to evict at time now using this precedence:
- If at least one item is expired, only expired items are eligible. An item is expired when
expirations[i] <= now. Return the smallest eligible key. - Otherwise, keep only items with the smallest priority value.
- If several items have that priority, choose the least recently used one: the item with the smallest
lastUsedvalue. - If a tie still remains, return the smallest key.
Function
selectEvictionKey(keys: int[], priorities: int[], expirations: int[], lastUsed: int[], now: int) → intExamples
Example 1
keys = [10,20,30]priorities = [5,1,1]expirations = [100,40,40]lastUsed = [9,8,7]now = 50return = 20Keys 20 and 30 are expired. Expiration takes precedence over priority and recency, and the smaller eligible key is 20.
Example 2
keys = [1,2,3,4]priorities = [2,1,1,3]expirations = [100,100,100,100]lastUsed = [5,8,3,1]now = 50return = 3No item is expired. Keys 2 and 3 have the minimum priority, and key 3 has the earlier last-used time.
Example 3
keys = [9,4]priorities = [1,1]expirations = [100,100]lastUsed = [7,7]now = 50return = 4The items tie on expiration status, priority, and recency, so the smaller key is returned.
Constraints
1 <= n <= 10^5.- All four arrays have length
n. - All keys are distinct.
0 <= keys[i], priorities[i], expirations[i], lastUsed[i], now <= 10^9.- Smaller
lastUsedvalues represent less recent access.