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 >
(self, start: int, end: int)
| 19 | self.prefix_sum[i] = self.prefix_sum[i - 1] + array[i] |
| 20 | |
| 21 | def get_sum(self, start: int, end: int) -> int: |
| 22 | """ |
| 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([]).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. |
| 41 | >>> PrefixSum([1,2,3]).get_sum(2, 3) |
| 42 | Traceback (most recent call last): |
| 43 | ... |
| 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. |
| 49 | """ |
| 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 | |
| 56 | if start == 0: |
| 57 | return self.prefix_sum[end] |
| 58 | |
| 59 | return self.prefix_sum[end] - self.prefix_sum[start - 1] |
| 60 | |
| 61 | def contains_sum(self, target_sum: int) -> bool: |
| 62 | """ |
nothing calls this directly
no outgoing calls
no test coverage detected