Skip to content

Commit 580273e

Browse files
pranjaykumar926pre-commit-ci[bot]MaximSmolskiy
authored
Improve prefix_sum.py (#12560)
* Update prefix_sum.py Index Validation for get_sum Raises ValueError if start or end is out of range or start > end. Handles cases where the array is empty. ✅ Empty Array Support If an empty array is passed, get_sum raises an appropriate error instead of failing unexpectedly. ✅ Optimized contains_sum Initialization Initializes sums with {0} for efficient subarray sum checking. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update prefix_sum.py * Update prefix_sum.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update prefix_sum.py * Update prefix_sum.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent edf7c37 commit 580273e

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

data_structures/arrays/prefix_sum.py

+19-1
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,29 @@ def get_sum(self, start: int, end: int) -> int:
3030
5
3131
>>> PrefixSum([1,2,3]).get_sum(2, 2)
3232
3
33+
>>> PrefixSum([]).get_sum(0, 0)
34+
Traceback (most recent call last):
35+
...
36+
ValueError: The array is empty.
37+
>>> PrefixSum([1,2,3]).get_sum(-1, 2)
38+
Traceback (most recent call last):
39+
...
40+
ValueError: Invalid range specified.
3341
>>> PrefixSum([1,2,3]).get_sum(2, 3)
3442
Traceback (most recent call last):
3543
...
36-
IndexError: list index out of range
44+
ValueError: Invalid range specified.
45+
>>> PrefixSum([1,2,3]).get_sum(2, 1)
46+
Traceback (most recent call last):
47+
...
48+
ValueError: Invalid range specified.
3749
"""
50+
if not self.prefix_sum:
51+
raise ValueError("The array is empty.")
52+
53+
if start < 0 or end >= len(self.prefix_sum) or start > end:
54+
raise ValueError("Invalid range specified.")
55+
3856
if start == 0:
3957
return self.prefix_sum[end]
4058

0 commit comments

Comments
 (0)