439. Allocate KV cache memory in pages, like vLLM
Paged attention splits the KV cache into fixed-size blocks, the way an operating system splits memory into pages. A request only grabs a new block when its current one is full, so memory is not reserved for tokens that never arrive.
Write allocate_blocks(requests, block_size, num_blocks). requests is a list of (request_id, num_tokens) in arrival order. Physical blocks are numbered 0 to num_blocks - 1 and are handed out lowest number first.
For each request, in order, give it ceil(num_tokens / block_size) blocks. If there are not enough free blocks left, skip that request entirely (it waits) and move on to the next.
Return a dict {request_id: [block numbers]} for the requests that fit.
def allocate_blocks(requests, block_size, num_blocks)Example 1
Input: requests = [("a", 20), ("b", 5)], block_size = 16, num_blocks = 4
Output: {"a": [0, 1], "b": [2]}
Example 2
Input: requests = [("a", 32)], block_size = 16, num_blocks = 4
Output: {"a": [0, 1]}
Constraints
- Python 3 standard library. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Blocks needed is ceil(n / block_size), which is -(-n // block_size).
Hint 2
Hand out the lowest free numbers and skip requests that do not fit.
Understand the idea
Paged attention stores each request's KV cache in small fixed-size blocks instead of one big reserved chunk, similar to how an operating system gives memory in pages. A request needs just enough blocks to hold its tokens, rounded up. Blocks are handed out from a free list, lowest number first, and a request that cannot get all its blocks is skipped without taking any, so a smaller later request may still fit.
block_size 4, num_blocks 4. Request A has 6 tokens, needing ceil(6/4) = 2 blocks, so it gets [0, 1]. Request B has 9 tokens, needing 3 blocks, but only 2 are free, so B is skipped. Request C has 3 tokens, needing 1 block, so it gets [2]. Result: {A: [0, 1], C: [2]}.
blocks needed = (tokens + block_size - 1) // block_size; allocate only if that many are free. vLLM uses this idea to serve many more requests on the same GPU
Companies3
- ByteDance the topic appears in interview reports ByteDance Machine Learning Engineer Interview Process
- Mistral the topic appears in interview reports Mistral AI Interview Guide 2026: European Frontier Lab, Open-Weight Strategy, MoE, and La Plateforme
- NVIDIA the topic appears in interview reports NVIDIA Interview Prep: Questions, Process & Study Plan
From public interview reports and guides. Not affiliated with or endorsed by these companies.