Check for Zero Sum Subarray in Python

 

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, otherwise False.

Logic Breakdown

  1. Initialize a set cumulative_sum_set to keep track of the cumulative sums encountered.
  2. Initialize a variable cumulative_sum to store the running total.
  3. 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 the cumulative_sum_set.
      If either condition is true, return True.
    • If not, add the cumulative_sum to the set for future reference.
  4. 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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *