Paginate and Budget-Trim a Chat History
Arrays & HashingAuto-graded · 14 test casesLast updated
Assemble a chronological transcript from paginated data, then reduce it to fit a token limit by removing the earliest messages.
You are building a context manager for a chat system that needs to load conversation history and keep it within a token budget for downstream processing.
Write a function that takes a list of pages and a token budget, then returns a two-element list:
- The complete transcript assembled from all pages
- The trimmed transcript that fits within the token budget
Each page in the input is a two-element list: [turn_list, next_cursor], where:
turn_listis a list of turn dictionaries, each with keys"id","speaker","text", and"token_count"next_cursoris either a string indicating more pages follow, orNonewhen this is the final page
Start reading from page index 0. Each time you see a non-None cursor, advance to the next page index. Stop when you encounter a None cursor.
When trimming to the budget, keep as many of the most recent turns as possible while ensuring the sum of their "token_count" values does not exceed the budget. Remove the oldest turns first.
Constraints
- 1 ≤ number of pages ≤ 100
- 0 ≤ turns per page ≤ 50
- 1 ≤ token_budget ≤ 10,000
- 1 ≤ token_count per turn ≤ 1,000
- All turn dictionaries contain the required keys
- Pages and turns within pages are in chronological order
- If the same cursor value appears twice, raise a
ValueError - The trimmed result should have total tokens ≤ budget (equality is allowed)
Examples
Example 1
Input: paginate_and_trim_chat([[[{'id': '1', 'speaker': 'customer', 'text': 'Hi', 'token_count': 2}], 'next'], [[{'id': '2', 'speaker': 'agent', 'text': 'Hello', 'token_count': 3}], None]], 4)
Output: [[{'id': '1', 'speaker': 'customer', 'text': 'Hi', 'token_count': 2}, {'id': '2', 'speaker': 'agent', 'text': 'Hello', 'token_count': 3}], [{'id': '2', 'speaker': 'agent', 'text': 'Hello', 'token_count': 3}]]
Example 2
Input: paginate_and_trim_chat([[[{'id': 'a', 'speaker': 'customer', 'text': 'Old', 'token_count': 5}], 'more'], [[], 'last'], [[{'id': 'b', 'speaker': 'agent', 'text': 'Recent', 'token_count': 2}], None]], 2)
Output: [[{'id': 'a', 'speaker': 'customer', 'text': 'Old', 'token_count': 5}, {'id': 'b', 'speaker': 'agent', 'text': 'Recent', 'token_count': 2}], [{'id': 'b', 'speaker': 'agent', 'text': 'Recent', 'token_count': 2}]]
Hints
Hint 1
Process pages sequentially by index, stopping only when you encounter a None cursor, not when a page is empty.
Hint 2
For trimming, iterate from the end of the transcript backward, accumulating tokens until adding another turn would exceed the budget.
Hint 3
Guard against infinite loops by tracking which cursor values you've already seen during pagination.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem has two distinct phases: pagination and budget trimming.
Pagination: Walk through the pages list by index, starting at 0. Extract the turn list and next cursor from each page, appending all turns to the growing transcript. Track which cursor values have been seen to detect loops—if the same cursor appears twice, the pagination is malformed and we raise an error. Continue until a page returns None as its cursor, signaling the end of the data.
Trimming: To keep the most recent turns while respecting the token budget, iterate backward through the full transcript. Maintain a running sum of token counts and collect turns as long as adding the next turn wouldn't push the total over the budget. Once done, reverse the collected turns to restore chronological order.
This approach is correct because:
- Pagination advances by index and terminates on the sentinel
Nonecursor, not on empty pages (which are valid intermediate results) - Trimming from the end naturally selects the most recent context
- The running total avoids repeatedly summing the same turns, keeping the trimming phase linear
Complexity
- Time: O(P + T) where P is the number of pages and T is the total number of turns. Pagination walks each page once, and trimming walks the transcript once.
- Space: O(T) to store the full transcript and the trimmed result. The cursor tracking set is O(P).
Solution
from typing import Dict, List
def paginate_and_trim_chat(pages: List[List], token_budget: int) -> List[List[Dict]]:
transcript = []
cursor = None
seen_cursors = set()
page_idx = 0
while True:
if cursor in seen_cursors:
raise ValueError("pagination cursor repeated")
seen_cursors.add(cursor)
if page_idx >= len(pages):
raise ValueError("missing page for cursor")
turn_list, next_cursor = pages[page_idx]
page_idx += 1
transcript.extend(turn_list)
if next_cursor is None:
break
cursor = next_cursor
trimmed = []
running_total = 0
for turn in reversed(transcript):
if running_total + turn["token_count"] > token_budget:
break
trimmed.append(turn)
running_total += turn["token_count"]
trimmed.reverse()
return [transcript, trimmed]