KatInterview

Paginate and Budget-Trim a Chat History

Arrays & HashingAuto-graded · 14 test cases
MediumAuto-gradedArrays & Hashingpaginationsliding-windowsimulation

Last 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:

  1. The complete transcript assembled from all pages
  2. 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_list is a list of turn dictionaries, each with keys "id", "speaker", "text", and "token_count"
  • next_cursor is either a string indicating more pages follow, or None when 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.