Python Program
def has_zero_sum_subarray(arr):
"""
Checks if there exists a subarray with a sum of zero.
Parameters:
arr (list of int): The input array to be checked.
Returns:
bool: True if a zero sum subarray exists, False otherwise.
"""
# Create a set to store the cumulative sum
cumulative_sum_set = set()
cumulative_sum = 0
for num in arr:
# Update the cumulative sum
cumulative_sum += num
# Check if the cumulative sum is zero or already in the set
if cumulative_sum == 0 or cumulative_sum in cumulative_sum_set:
return True
# Add the cumulative sum to the set
cumulative_sum_set.add(cumulative_sum)
return False
# Example usage
if __name__ == "__main__":
arr = [4, 2, -3, 1, 6]
result = has_zero_sum_subarray(arr)
print("Zero sum subarray exists:" if result else "No zero sum subarray exists.")
Program Explanation
The program defines a function has_zero_sum_subarray
that checks for the existence of a subarray with a sum of zero.
Function Structure
- Input: A list of integers,
arr
. - Output: A boolean value:
True
if a zero-sum subarray exists, otherwiseFalse
.
Logic Breakdown
- Initialize a set
cumulative_sum_set
to keep track of the cumulative sums encountered. - Initialize a variable
cumulative_sum
to store the running total. - Loop through each element
num
in the array:- Update the
cumulative_sum
by adding the current number. - Check if
cumulative_sum
is zero or already exists in thecumulative_sum_set
.
If either condition is true, returnTrue
. - If not, add the
cumulative_sum
to the set for future reference.
- Update the
- If the loop completes without finding a zero-sum subarray, return
False
.
Example Usage
In the example provided, the array [4, 2, -3, 1, 6]
is checked. The program will output:
"Zero sum subarray exists:"
indicating that there is a subarray (specifically [2, -3, 1]
) that sums to zero.