Python Program to Find if there is a subarray with 0 sum

Python Program to Find if there is a subarray with 0 sum

Finding if there exists a subarray with a sum of 0 can be done efficiently with the help of a hash set. The idea is to maintain a prefix sum as we iterate through the array. If at any point the prefix sum is 0 or the same prefix sum value occurs again, then there exists a subarray with a sum of 0.

Here's how you can do this:

def is_subarray_zero_sum(arr): # Create a set to store prefix sums prefix_sum_set = set() prefix_sum = 0 for num in arr: prefix_sum += num # If prefix sum is 0 or it already exists in set then there's a subarray with sum 0 if prefix_sum == 0 or prefix_sum in prefix_sum_set: return True prefix_sum_set.add(prefix_sum) return False # Test the function arr = [4, 2, -3, 1, 6] print(is_subarray_zero_sum(arr)) # True because there's a subarray [2, -3, 1] with sum 0 

In the above code:

  • We keep track of the prefix sum as we traverse through the array.
  • If at any point the prefix sum becomes 0, or if the same prefix sum has been observed before (indicating a subarray sum of 0), we return True.
  • If we go through the entire array without finding a sum of 0, we return False.

More Tags

postgresql-9.1 linegraph database-administration bootstrap-selectpicker expo qdialog intervention soap reboot string-comparison

More Programming Guides

Other Guides

More Programming Examples