Skip to content

Update prefix_sum.py #12560

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 19, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion data_structures/arrays/prefix_sum.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,29 @@ def get_sum(self, start: int, end: int) -> int:
5
>>> PrefixSum([1,2,3]).get_sum(2, 2)
3
>>> PrefixSum([]).get_sum(0, 0)
Traceback (most recent call last):
...
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):
...
IndexError: list index out of range
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]

Expand Down