TheAlgorithms/Python · error · ValueError
Window size must be a positive integer
Error message
Window size must be a positive integer
What it means
Raised by sliding_window_maximum when window_size is <= 0. The deque-based algorithm assumes each window covers at least one element, so zero or negative window sizes are rejected up front. An empty numbers list is legal and returns [] — only the window size is validated.
Source
Thrown at other/sliding_window_maximum.py:36
ValueError: If window_size is not a positive integer.
Time Complexity: O(n) - each element is added and removed at most once
Space Complexity: O(k) - deque stores at most window_size indices
Examples:
>>> sliding_window_maximum([1, 3, -1, -3, 5, 3, 6, 7], 3)
[3, 3, 5, 5, 6, 7]
>>> sliding_window_maximum([9, 11], 2)
[11]
>>> sliding_window_maximum([], 3)
[]
>>> sliding_window_maximum([4, 2, 12, 3], 1)
[4, 2, 12, 3]
>>> sliding_window_maximum([1], 1)
[1]
"""
if window_size <= 0:
raise ValueError("Window size must be a positive integer")
if not numbers:
return []
result: list[int] = []
index_deque: deque[int] = deque()
for current_index, current_value in enumerate(numbers):
# Remove the element which is out of this window
if index_deque and index_deque[0] == current_index - window_size:
index_deque.popleft()
# Remove useless elements (smaller than current) from back
while index_deque and numbers[index_deque[-1]] < current_value:
index_deque.pop()
index_deque.append(current_index)
# Start adding to result once we have a full windowView on GitHub (pinned to f5988cc097)
Solutions
- Pass a positive window size (>= 1); window_size=1 returns the input unchanged
- Clamp computed sizes: window_size = max(1, window_size)
- Validate config before the call and raise a clear upstream error if an invalid size is configured
Example fix
# before result = sliding_window_maximum(nums, len(nums) - k) # k >= len(nums) -> 0 or negative # after result = sliding_window_maximum(nums, max(1, len(nums) - k))
Defensive patterns
Strategy: validation
Validate before calling
def valid_window_size(window_size) -> bool:
return isinstance(window_size, int) and window_size >= 1 Prevention
- Clamp computed window sizes with max(1, k)
- Validate window parameters from config against positive integers at load time
When it happens
Trigger: Calling sliding_window_maximum([1,2,3], 0), sliding_window_maximum([1,2,3], -2), or passing a window size computed from an expression that can reach 0.
Common situations: Window size derived from user configuration or from a formula like len(numbers) - k that can hit zero or below on short inputs.
Related errors
- Invalid value for min_val or max_val (min_value < max_value)
- argument value for lower and higher must be(lower > higher)
- guess value must be within the range of lower and higher val
- Impossible fluid density
- Impossible object volume
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/33cd3c4f199c0aa3.
Report an issue: GitHub.