FastPrepPriority, Expiration, and LRU Eviction

Priority, Expiration, and LRU Eviction

Tesla logoTesla● MediumFULLTIMEPHONE SCREEN
Learn

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:

  1. 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.
  2. Otherwise, keep only items with the smallest priority value.
  3. If several items have that priority, choose the least recently used one: the item with the smallest lastUsed value.
  4. If a tie still remains, return the smallest key.

Function

selectEvictionKey(keys: int[], priorities: int[], expirations: int[], lastUsed: int[], now: int) → int

Examples

Example 1

keys = [10,20,30]priorities = [5,1,1]expirations = [100,40,40]lastUsed = [9,8,7]now = 50return = 20

Keys 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 = 3

No 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 = 4

The 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 lastUsed values represent less recent access.

More Tesla problems

See Tesla hiring insights
public int selectEvictionKey(int[] keys, int[] priorities, int[] expirations, int[] lastUsed, int now) {
  // write your code here
}
keys[10,20,30]
priorities[5,1,1]
expirations[100,40,40]
lastUsed[9,8,7]
now50
expected20
Checking account…