Trim History to a Token Budget
Every agent turn re-sends the whole conversation, so the history has to fit the context budget. The standard move: keep the most recent messages that fit and drop the oldest. Implement the trimmer at the heart of context management.
The problem
Implement trim_history(counts, budget). counts is a list of the token counts of the messages in a conversation, oldest first. Keep as many of the most recent messages as fit within budget tokens (walking from the end, stopping at the first message that would push the total over budget), and return their counts in original order.
counts=[5, 5, 5, 5], budget=12[5, 5]counts=[10, 1, 1, 1], budget=3[1, 1, 1]counts=[100], budget=50[]- Keep the most recent messages — walk from the end and stop at the first that would exceed the budget.
- Return the kept counts in their original (oldest-first) order.
- The kept messages form a contiguous suffix of the input.
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement trim_history(counts, budget) — keep the most recent messages that fit the token budget, drop the oldest, and return the kept counts oldest-first.
- Iterate the list in reverse (newest first), accumulating a running total.
- Stop as soon as adding the next message would exceed the budget.
- Collect the kept counts, then restore their original order before returning.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.