Measure LRU Cache Hits and Misses for an Access Workload
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Measure cache hits and misses for an access workload handled by a least recently used (LRU) cache.
### Function Contract
Implement `lru_hit_miss_counts(capacity, requests) -> list[int]`.
The cache starts empty. `requests` lists integer keys accessed in order. Apply these explicit workload rules:
- Accessing a cached key is a hit and makes that key most recently used.
- Accessing an uncached key is a miss. If capacity is positive, insert it as most recently used, evicting the least recently used key first if the cache is full.
- At capacity zero, every request is a miss and nothing is stored.
Return `[hit_count, miss_count]`. These counters determine the hit ratio `hit_count / n` and miss ratio `miss_count / n` for a nonempty workload of length `n`. For an empty workload, return `[0, 0]`; no ratio is defined.
### Constraints and Clarifications
- `0 <= capacity <= 200000`.
- `0 <= len(requests) <= 200000`.
- Each key is an integer from `0` through `1000000000`.
- Capacity counts keys, and every key occupies one slot.
- There is no expiration, prefetching, or write policy in this exercise.
- Aim for expected `O(n)` total time with `O(min(capacity, n))` cache storage.
### Examples
```text
capacity = 2
requests = [1, 2, 1, 3, 2, 3]
Output: [2, 4]
```
The repeated accesses to `1` at the third request and `3` at the last request are hits. The hit ratio is `2/6`, and the miss ratio is `4/6`.
```text
capacity = 0
requests = [5, 5, 5]
Output: [0, 3]
```
```hint Recency changes on a hit too
Keeping insertion order is insufficient when an existing key is accessed again. Track the ordering needed to identify the next eviction without scanning the entire cache.
```
Overview: Simulate an LRU cache with hit and miss counters, correct recency updates, bounded capacity, and explicit empty-workload behavior.
The cache starts empty. requests lists integer keys accessed in order. Apply these explicit workload rules:
Accessing a cached key is a hit and makes that key most recently used.
Accessing an uncached key is a miss. If capacity is positive, insert it as most recently used, evicting the least recently used key first if the cache is full.
At capacity zero, every request is a miss and nothing is stored.
Return [hit_count, miss_count]. These counters determine the hit ratio hit_count / n and miss ratio miss_count / n for a nonempty workload of length n. For an empty workload, return [0, 0]; no ratio is defined.
Constraints and Clarifications
0 <= capacity <= 200000
.
0 <= len(requests) <= 200000
.
Each key is an integer from
0
through
1000000000
.
Capacity counts keys, and every key occupies one slot.
There is no expiration, prefetching, or write policy in this exercise.
Aim for expected
O(n)
total time with
O(min(capacity, n))
cache storage.