KatInterview

Trim a Record List to a Token Budget with a Sliding Window

Arrays & HashingAuto-graded · 15 test cases
MediumAuto-gradedArrays & Hashingsliding-windowarraystwo-pointers

Last updated

Tests the sliding-window technique: conditionally compact a list of records to the longest contiguous run whose token sum fits a given budget.

You are given a list of records. Each record is a dictionary containing, among other fields, a "tokens" key whose value is a non-negative integer representing how many tokens that record consumes.

Task

Write compact_records(records, trigger, target).

  1. Sum the "tokens" values across all records.
  2. If the total is at most trigger, return the list unchanged.
  3. Otherwise, find the longest contiguous subarray of records whose token sum is at most target, and return it.
    • "Contiguous" means the records must appear consecutively in the original list and in their original order.
    • If multiple subarrays share the same maximum length, return the earliest one (lowest starting index).
    • If no single record fits within target, return an empty list.

Constraints

  • 1 <= len(records) <= 10^5
  • 0 <= record["tokens"] <= 10^5 for every record
  • 1 <= target <= trigger <= 10^9
  • Each record is a dict with at least a "tokens" key; all other keys must be preserved unchanged in the output.
  • The function must run in O(n) time.

Examples

Example 1

Input: compact_records([{'tokens': 4000}, {'tokens': 3000}, {'tokens': 5000}, {'tokens': 2000}, {'tokens': 1000}, {'tokens': 6000}, {'tokens': 3000}])

Output: [{'tokens': 3000}, {'tokens': 5000}, {'tokens': 2000}]

Hints

Hint 1

Start by summing all token values. You only need the sliding-window logic when that sum exceeds the trigger — otherwise return immediately.

Hint 2

Use two pointers (left and right) that both move strictly forward. Advance right to grow the window, then shrink from the left only when the window's token sum exceeds the target. Neither pointer ever moves backward, giving O(n) overall.

Hint 3

Track the best window as (best_length, best_start). Update it after each shrink step, when the current window is guaranteed to fit within target. Only update on a strictly greater length so ties resolve in favour of the earlier start index.