
Fill the context window
mediumFill the context window
Anthropic RAG Interview Question
Retrieval returns more chunks than fit in the prompt, so the best ones have to be chosen against a token budget.
Write a function pack(chunks, budget) that takes the highest scoring chunks whose token counts add up to no more than the budget. Consider chunks from the highest score down, breaking ties by id alphabetically. When a chunk does not fit, skip it and carry on to the next one, since a smaller chunk further down may still fit. Return the ids of the chunks taken, in the order they were taken.
Asked of
- AI Engineer
- ML Engineer
- Data Scientist
Example 1
Input
chunks = [{"id": "a", "tokens": 60, "score": 0.9}, {"id": "b", "tokens": 50, "score": 0.8}, {"id": "c", "tokens": 30, "score": 0.7}], budget = 100Output
["a", "c"]
Example 2
Input
chunks = [{"id": "big", "tokens": 500, "score": 1}], budget = 100Output
[]
Explanation
In the first example "a" takes 60 of the 100 tokens. "b" needs 50 and does not fit, so it is skipped. "c" needs 30, which fits in what is left.
Submit also runs 2 hidden test cases that check edge cases.
- Token budget
Similar questions
Company
Anthropic
Difficulty
medium
Topic
RAG
Language
Python
Your code
Loading Python in the background. You can start writing.