Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9f11be6

Browse files
authoredOct 18, 2024··
Update prefix_sum.py
I have updated prefix_sum.py with the following changes:- 1. get_sum: Added an explicit check for invalid ranges and index out-of-bounds cases. 2. contains_sum: Fixed a logic issue where the target sum equal to the first prefix sum wouldn't be detected. 3. Updated the space complexity note in get_sum.
1 parent 03a4251 commit 9f11be6

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed
 

‎data_structures/arrays/prefix_sum.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
1-
"""
2-
Author : Alexander Pantyukhin
3-
Date : November 3, 2022
41

52
Implement the class of prefix sum with useful functions based on it.
63

7-
"""
8-
9-
104
class PrefixSum:
115
def __init__(self, array: list[int]) -> None:
126
len_array = len(array)
@@ -22,7 +16,7 @@ def get_sum(self, start: int, end: int) -> int:
2216
"""
2317
The function returns the sum of array from the start to the end indexes.
2418
Runtime : O(1)
25-
Space: O(1)
19+
Space: O(n) (due to the prefix sum array)
2620
2721
>>> PrefixSum([1,2,3]).get_sum(0, 2)
2822
6
@@ -35,14 +29,17 @@ def get_sum(self, start: int, end: int) -> int:
3529
...
3630
IndexError: list index out of range
3731
"""
32+
if start > end or end >= len(self.prefix_sum):
33+
raise IndexError("Invalid range specified.")
34+
3835
if start == 0:
3936
return self.prefix_sum[end]
4037

4138
return self.prefix_sum[end] - self.prefix_sum[start - 1]
4239

4340
def contains_sum(self, target_sum: int) -> bool:
4441
"""
45-
The function returns True if array contains the target_sum,
42+
The function returns True if any subarray contains the target_sum,
4643
False otherwise.
4744
4845
Runtime : O(n)
@@ -64,7 +61,7 @@ def contains_sum(self, target_sum: int) -> bool:
6461

6562
sums = {0}
6663
for sum_item in self.prefix_sum:
67-
if sum_item - target_sum in sums:
64+
if sum_item == target_sum or sum_item - target_sum in sums:
6865
return True
6966

7067
sums.add(sum_item)
@@ -76,3 +73,9 @@ def contains_sum(self, target_sum: int) -> bool:
7673
import doctest
7774

7875
doctest.testmod()
76+
77+
78+
79+
80+
81+

0 commit comments

Comments
 (0)
Please sign in to comment.