forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefix_sum.py
78 lines (60 loc) · 1.89 KB
/
prefix_sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
Author : Alexander Pantyukhin
Date : November 3, 2022
Implement the class of prefix sum with useful functions based on it.
"""
class PrefixSum:
def __init__(self, array: list[int]) -> None:
len_array = len(array)
self.prefix_sum = [0] * len_array
if len_array > 0:
self.prefix_sum[0] = array[0]
for i in range(1, len_array):
self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i]
def get_sum(self, start: int, end: int) -> int:
"""
The function returns the sum of array from the start to the end indexes.
Runtime : O(1)
Space: O(1)
>>> PrefixSum([1,2,3]).get_sum(0, 2)
6
>>> PrefixSum([1,2,3]).get_sum(1, 2)
5
>>> PrefixSum([1,2,3]).get_sum(2, 2)
3
>>> PrefixSum([1,2,3]).get_sum(2, 3)
Traceback (most recent call last):
...
IndexError: list index out of range
"""
if start == 0:
return self.prefix_sum[end]
return self.prefix_sum[end] - self.prefix_sum[start - 1]
def contains_sum(self, target_sum: int) -> bool:
"""
The function returns True if array contains the target_sum,
False otherwise.
Runtime : O(n)
Space: O(n)
>>> PrefixSum([1,2,3]).contains_sum(6)
True
>>> PrefixSum([1,2,3]).contains_sum(5)
True
>>> PrefixSum([1,2,3]).contains_sum(3)
True
>>> PrefixSum([1,2,3]).contains_sum(4)
False
>>> PrefixSum([1,2,3]).contains_sum(7)
False
>>> PrefixSum([1,-2,3]).contains_sum(2)
True
"""
sums = {0}
for sum_item in self.prefix_sum:
if sum_item - target_sum in sums:
return True
sums.add(sum_item)
return False
if __name__ == "__main__":
import doctest
doctest.testmod()