From fd4755c7e3b5074b97b84fe54a07eab4e3b90774 Mon Sep 17 00:00:00 2001 From: Kusum Kharayat Date: Fri, 18 Oct 2024 10:36:19 +0530 Subject: [PATCH 1/2] Update prefix_sum.py I have updated this file 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. --- data_structures/arrays/prefix_sum.py | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/data_structures/arrays/prefix_sum.py b/data_structures/arrays/prefix_sum.py index 2243a5308937..c2e0fa8921e7 100644 --- a/data_structures/arrays/prefix_sum.py +++ b/data_structures/arrays/prefix_sum.py @@ -1,12 +1,6 @@ -""" -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) @@ -22,7 +16,7 @@ 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) + Space: O(n) (due to the prefix sum array) >>> PrefixSum([1,2,3]).get_sum(0, 2) 6 @@ -35,6 +29,9 @@ def get_sum(self, start: int, end: int) -> int: ... IndexError: list index out of range """ + if start > end or end >= len(self.prefix_sum): + raise IndexError("Invalid range specified.") + if start == 0: return self.prefix_sum[end] @@ -42,7 +39,7 @@ def get_sum(self, start: int, end: int) -> int: def contains_sum(self, target_sum: int) -> bool: """ - The function returns True if array contains the target_sum, + The function returns True if any subarray contains the target_sum, False otherwise. Runtime : O(n) @@ -64,7 +61,7 @@ def contains_sum(self, target_sum: int) -> bool: sums = {0} for sum_item in self.prefix_sum: - if sum_item - target_sum in sums: + if sum_item == target_sum or sum_item - target_sum in sums: return True sums.add(sum_item) @@ -76,3 +73,10 @@ def contains_sum(self, target_sum: int) -> bool: import doctest doctest.testmod() + + + + + + + From 05c9fef8f87d0fc24f32e78373ffbb90ba9085c9 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 18 Oct 2024 05:09:36 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- data_structures/arrays/prefix_sum.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/data_structures/arrays/prefix_sum.py b/data_structures/arrays/prefix_sum.py index c2e0fa8921e7..26a63371ef6b 100644 --- a/data_structures/arrays/prefix_sum.py +++ b/data_structures/arrays/prefix_sum.py @@ -74,9 +74,9 @@ def contains_sum(self, target_sum: int) -> bool: doctest.testmod() - - - - - + + + + +