Skip to content

Commit b0d0021

Browse files
Update prefix_sum.py
1 parent c8a345e commit b0d0021

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

data_structures/arrays/prefix_sum.py

+27-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
"""
2+
Author : Alexander Pantyukhin
3+
Date : November 3, 2022
4+
Implement the class of prefix sum with useful functions based on it.
5+
"""
6+
7+
18
class PrefixSum:
29
def __init__(self, array: list[int]) -> None:
310
len_array = len(array)
@@ -28,12 +35,29 @@ def get_sum(self, start: int, end: int) -> int:
2835

2936
def contains_sum(self, target_sum: int) -> bool:
3037
"""
31-
Returns True if any subarray sum equals target_sum, otherwise False.
38+
The function returns True if array contains the target_sum,
39+
False otherwise.
40+
Runtime : O(n)
41+
Space: O(n)
42+
>>> PrefixSum([1,2,3]).contains_sum(6)
43+
True
44+
>>> PrefixSum([1,2,3]).contains_sum(5)
45+
True
46+
>>> PrefixSum([1,2,3]).contains_sum(3)
47+
True
48+
>>> PrefixSum([1,2,3]).contains_sum(4)
49+
False
50+
>>> PrefixSum([1,2,3]).contains_sum(7)
51+
False
52+
>>> PrefixSum([1,-2,3]).contains_sum(2)
53+
True
3254
"""
33-
sums = {0} # Initialize with 0 to check subarrays from the start
55+
56+
sums = {0}
3457
for sum_item in self.prefix_sum:
35-
if (sum_item - target_sum) in sums:
58+
if sum_item - target_sum in sums:
3659
return True
60+
3761
sums.add(sum_item)
3862

3963
return False

0 commit comments

Comments
 (0)