Trim Chat History to Fit a Model Context Budget

Last updated: November 29, 2026

Quick Overview

Given a list of chat messages (system, user, assistant) and a token budget, return the subset to send to the model: always keep system messages, then keep the most recent turns that fit, preserving order.

Mistral AI
Coding & Algorithms
Software Engineer
Mistral AI
November 29, 2026
Software Engineer
Phone Screen
Coding & Algorithms
Easy

0

0

0 solved


Given a list of chat messages (system, user, assistant) and a token budget, return the subset to send to the model: always keep system messages, then keep the most recent turns that fit, preserving order.

A warm-up in the style of a Mistral AI backend or Le Chat engineering screen, where long conversations must be cut down before hitting a model's context window. The interviewer checks clean greedy logic, that order is preserved, and that you think about what truncation does to conversation coherence.

What the Interviewer Expects
  • Always keep system messages and fail loudly if they alone exceed the budget
  • Walk from newest to oldest and stop at the first message that does not fit
  • Return messages in original order
  • Treat the tokenizer as an injected function rather than hard-coding word counts
  • Discuss coherence issues such as starting on an orphaned assistant turn
Key Topics to Cover
Greedy selection
Context window
Tokenization
Chat templates
Order preservation
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you keep tool-call and tool-result messages together as one unit?
  • How would you reserve room for the model's reply (max_tokens)?
  • When would you summarize dropped turns instead of discarding them?
  • How do you avoid re-tokenizing the whole history on every request?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Input: messages (dicts with role, content), an integer budget, and count_tokens(text). Output: a list in original order where system messages are always present and the remaining slots go to...

High-Level Design
  1. Sum the cost of all system messages; error if over budget.
  2. Iterate from the last message backwards, adding each non-system message while it fits.
  3. Stop at the first one that does not fit, so t...

Submit Your Answer
Markdown supported

Related Questions