PIXELBANKv9.1.0
Menu

Sliding Window Keeping the System Message

Problem Statement

Keep an agent's context small by retaining only the most recent turns — but never drop the leading system message, which sets the agent's instructions.

Background

A message list starts with an optional system message (role "system") followed by alternating user/assistant turns. A sliding window keeps the last k non-system messages. If the first message is a system message it is always preserved and prepended to the kept window.

Your Task

Implement:

def sliding_window(messages, k):
  • If messages[0]["role"] == "system", always keep it.
  • Keep the last k of the remaining (non-system-prefix) messages, in order.
  • Return the new list.

Input Format

  • messages: list of {"role", "content"} dicts.
  • k (int): number of recent non-system messages to keep.

Output Format

  • A list of message dicts.

Sample

msgs = [{"role":"system","content":"S"},{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":"c"}]
print(sliding_window(msgs, 2))

Output:

[{'role': 'system', 'content': 'S'}, {'role': 'assistant', 'content': 'b'}, {'role': 'user', 'content': 'c'}]

Example:

Input:
msgs = [{"role":"system","content":"S"},{"role":"user","content":"a"},{"role":"assistant","content":"b"},{"role":"user","content":"c"}]
print(sliding_window(msgs, 2))
Output:
[{'role': 'system', 'content': 'S'}, {'role': 'assistant', 'content': 'b'}, {'role': 'user', 'content': 'c'}]
Reasoning:
  • Identify the leading system message: Since the first message has role "system", it is separated and preserved as the prefix head = [{"role":"system","content":"S"}].
  • Isolate the remaining conversation turns: The non-system messages form the list rest = [{"role":"user","content":"a"}, {"role":"assistant","content":"b"}, {"role":"user","content":"c"}], which has a length of 3.
  • Apply the sliding window constraint: With k=2k=2, we need the last 2 messages from rest. Using the slice logic, we take elements from index 3−2=13 - 2 = 1 to the end, resulting in kept = [{"role":"assistant","content":"b"}, {"role":"user","content":"c"}].
  • Combine the preserved prefix with the recent window: Concatenate head and kept to form the final list [{"role":"system","content":"S"}, {"role":"assistant","content":"b"}, {"role":"user","content":"c"}].
  • The final output is [{'role': 'system', 'content': 'S'}, {'role': 'assistant', 'content': 'b'}, {'role': 'user', 'content': 'c'}]

Constraints:

  • 0 <= k <= len(messages).
  • Only a leading system message is special; system messages elsewhere are treated normally.
  • Preserve original order.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Sliding Window Keeping the System Message - Easy | PixelBank