TheAlgorithms/Python · error · ValueError
Invalid range specified.
Error message
Invalid range specified.
What it means
Raised by PrefixSum.get_sum() in data_structures/arrays/prefix_sum.py when the requested [start, end] range is invalid for the populated array: start < 0, end >= len(prefix_sum), or start > end. Valid ranges are inclusive on both ends within array bounds.
Source
Thrown at data_structures/arrays/prefix_sum.py:54
ValueError: The array is empty.
>>> PrefixSum([1,2,3]).get_sum(-1, 2)
Traceback (most recent call last):
...
ValueError: Invalid range specified.
>>> PrefixSum([1,2,3]).get_sum(2, 3)
Traceback (most recent call last):
...
ValueError: Invalid range specified.
>>> PrefixSum([1,2,3]).get_sum(2, 1)
Traceback (most recent call last):
...
ValueError: Invalid range specified.
"""
if not self.prefix_sum:
raise ValueError("The array is empty.")
if start < 0 or end >= len(self.prefix_sum) or start > end:
raise ValueError("Invalid range specified.")
if start == 0:
return self.prefix_sum[end]
return self.prefix_sum[end] - self.prefix_sum[start - 1]
def contains_sum(self, target_sum: int) -> bool:
"""
The function returns True if array contains the target_sum,
False otherwise.
Runtime : O(n)
Space: O(n)
>>> PrefixSum([1,2,3]).contains_sum(6)
True
>>> PrefixSum([1,2,3]).contains_sum(5)
TrueView on GitHub (pinned to f5988cc097)
Solutions
- Remember both bounds are inclusive: the last valid end is len(arr) - 1, not len(arr).
- Normalize arguments before calling: if start > end: start, end = end, start.
- Validate: 0 <= start <= end < len(arr) before invoking get_sum.
Example fix
# before ps.get_sum(0, len(arr)) # end one past the last index # after ps.get_sum(0, len(arr) - 1) # inclusive end
Defensive patterns
Strategy: validation
Validate before calling
n = len(arr)
start, end = max(0, start), min(end, n - 1)
if start > end:
raise ValueError('empty normalized range')
total = ps.get_sum(start, end) Prevention
- Both bounds are inclusive: last valid end is len(arr) - 1
- Swap swapped bounds before calling
- Validate 0 <= start <= end < len(arr)
When it happens
Trigger: Calling get_sum(2, 3) or get_sum(2, 1) on PrefixSum([1,2,3]) (end 3 out of bounds; start > end), get_sum(-1, 2), or get_sum(0, n) where n == len(arr) — the classic inclusive-end off-by-one.
Common situations: Treating end as exclusive when it is inclusive (passing len(arr) instead of len(arr)-1), reversed bounds from swapped arguments, or ranges computed from user input without bound checks.
Related errors
- The array is empty.
- The parameter idx_original_string must be lower than len(bwt
- index out of range
- Invalid value of 'position'
- list index out of range
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/84d37d89ad8f30d5.
Report an issue: GitHub.