Skip to content

Commit cae97f0

Browse files
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.
1 parent 6c92c5a commit cae97f0

File tree

1 file changed

+11
-49
lines changed

1 file changed

+11
-49
lines changed

data_structures/arrays/prefix_sum.py

+11-49
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,3 @@
1-
"""
2-
Author : Alexander Pantyukhin
3-
Date : November 3, 2022
4-
5-
Implement the class of prefix sum with useful functions based on it.
6-
7-
"""
8-
9-
101
class PrefixSum:
112
def __init__(self, array: list[int]) -> None:
123
len_array = len(array)
@@ -20,59 +11,30 @@ def __init__(self, array: list[int]) -> None:
2011

2112
def get_sum(self, start: int, end: int) -> int:
2213
"""
23-
The function returns the sum of array from the start to the end indexes.
24-
Runtime : O(1)
25-
Space: O(1)
26-
27-
>>> PrefixSum([1,2,3]).get_sum(0, 2)
28-
6
29-
>>> PrefixSum([1,2,3]).get_sum(1, 2)
30-
5
31-
>>> PrefixSum([1,2,3]).get_sum(2, 2)
32-
3
33-
>>> PrefixSum([1,2,3]).get_sum(2, 3)
34-
Traceback (most recent call last):
35-
...
36-
IndexError: list index out of range
14+
Returns the sum of the array from index start to end (inclusive).
15+
Raises ValueError if the indices are invalid.
3716
"""
38-
if start == 0:
39-
return self.prefix_sum[end]
17+
if not self.prefix_sum:
18+
raise ValueError("The array is empty.")
19+
20+
if start < 0 or end >= len(self.prefix_sum) or start > end:
21+
raise ValueError("Invalid range specified.")
4022

41-
return self.prefix_sum[end] - self.prefix_sum[start - 1]
23+
return self.prefix_sum[end] if start == 0 else self.prefix_sum[end] - self.prefix_sum[start - 1]
4224

4325
def contains_sum(self, target_sum: int) -> bool:
4426
"""
45-
The function returns True if array contains the target_sum,
46-
False otherwise.
47-
48-
Runtime : O(n)
49-
Space: O(n)
50-
51-
>>> PrefixSum([1,2,3]).contains_sum(6)
52-
True
53-
>>> PrefixSum([1,2,3]).contains_sum(5)
54-
True
55-
>>> PrefixSum([1,2,3]).contains_sum(3)
56-
True
57-
>>> PrefixSum([1,2,3]).contains_sum(4)
58-
False
59-
>>> PrefixSum([1,2,3]).contains_sum(7)
60-
False
61-
>>> PrefixSum([1,-2,3]).contains_sum(2)
62-
True
27+
Returns True if any subarray sum equals target_sum, otherwise False.
6328
"""
64-
65-
sums = {0}
29+
sums = {0} # Initialize with 0 to check subarrays from the start
6630
for sum_item in self.prefix_sum:
67-
if sum_item - target_sum in sums:
31+
if (sum_item - target_sum) in sums:
6832
return True
69-
7033
sums.add(sum_item)
7134

7235
return False
7336

7437

7538
if __name__ == "__main__":
7639
import doctest
77-
7840
doctest.testmod()

0 commit comments

Comments
 (0)