Trim a Record List to a Token Budget with a Sliding Window
Arrays & HashingAuto-graded · 15 test casesLast 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).
- Sum the
"tokens"values across all records. - If the total is at most
trigger, return the list unchanged. - Otherwise, find the longest contiguous subarray of
recordswhose token sum is at mosttarget, 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^50 <= record["tokens"] <= 10^5for every record1 <= target <= trigger <= 10^9- Each record is a
dictwith 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Step 1 — decide whether to act
Sum every record's "tokens" value. If the total is at or below trigger, the list already satisfies the constraint and is returned unchanged. This avoids unnecessary work for the common case.
Step 2 — sliding window
Once compaction is required, the goal is: find the longest contiguous subarray with token sum ≤ target.
Maintain two pointers, left and right, defining the current window records[left..right].
- Advance
rightby one step, adding the new record's tokens towindow_sum. - If
window_sumnow exceedstarget, advanceleft(subtracting its tokens) until the window fits again. - After each right-step the window is guaranteed to fit. Compare its length against the best seen so far, updating only on a strict improvement (
length > best_length). This ensures ties resolve in favour of the earliest window.
Both pointers move strictly forward, so each record enters and leaves the window at most once.
Why it is correct
After the shrink loop, every index from left to right is included in a window whose sum is ≤ target by construction. The window cannot be wider to the right because that step has not been processed yet, and it cannot be wider to the left without exceeding the target because the shrink loop stopped as soon as the budget was satisfied. Therefore the window at each step is the widest window ending at right that fits, and keeping a running maximum over all such windows yields the globally longest valid subarray.
Edge cases
| Situation | Behaviour |
|---|---|
| Total ≤ trigger | Original list returned immediately |
Every single record exceeds target | Every window shrinks to width 0; best_length stays 0; empty list returned |
| A record with 0 tokens | Window sum unchanged; handled naturally |
| All records have 0 tokens | Entire list fits any target; full list returned from the unchanged-total branch or as a width-n window |
Complexity
- Time: O(n) — each pointer traverses the list at most once.
- Space: O(1) extra — only a handful of integer variables; the returned value is a slice of the original list.
Reference solution
from typing import List, Dict
def compact_records(records: List[Dict], trigger: int = 20000, target: int = 10000) -> List[Dict]:
# Step 1: check whether compaction is needed at all.
total = sum(r["tokens"] for r in records)
if total <= trigger:
return records
# Step 2: sliding window — find the longest subarray with sum <= target.
best_start = 0
best_length = 0
left = 0
window_sum = 0
for right, record in enumerate(records):
window_sum += record["tokens"]
# Shrink from the left until the window fits within the target.
while left <= right and window_sum > target:
window_sum -= records[left]["tokens"]
left += 1
# Window [left, right] now fits; update best only on strict improvement
# so that ties keep the earliest (first-seen) starting index.
length = right - left + 1
if length > best_length:
best_start = left
best_length = length
return records[best_start : best_start + best_length]