← 返回 tesla 的题目列表Priority + Expiration + LRU Eviction
类型:qbank
Implement `evictItem()` for a cache-like class that already has `set(key, value, priority, expiretime)` and `get(key)`. Expired items are evicted first; otherwise lowest priority wins; ties break by least-recently-used.
Requirements
Class has existing black-box methods: set(key, value, priority, expiretime) and get(key).
Implement evictItem() only.
Each item has key, value, priority, and expiretime.
Eviction order:
If any item is expired, evict an expired item first.
If no item is expired, evict the lowest-priority item.
If priorities tie, evict the least-recently-used item.
Notes
The data-structure design needs indexes for expiration, priority, and recency. A practical answer uses a min-heap by expiration for expired candidates, a min-heap by (priority, last_access_time) for normal eviction, and lazy deletion to handle stale heap entries.
get(key) must update recency if the existing class does not already do it. If get is truly black-box and cannot be changed, clarify where last-access time is maintained.
Lazy deletion needs a version or pointer identity check; otherwise an old heap entry can evict a key after set has updated its priority or expiration.
Define how to break ties among multiple expired items: earliest expiration is the natural choice unless the interviewer specifies otherwise.
Preparation
Implement evictItem() using store[key] -> item/version, expiry_heap, and priority_lru_heap; write a helper that pops stale heap entries until the top matches the current store.
Drill the cache patterns behind the prompt: LRU for recency tie-breaks and LFU-style bucket thinking for ordered eviction criteria.
Test expired-first behavior, priority ties, get recency updates, set updates that leave stale heap entries behind, empty cache, and identical timestamps.