Check if a Subarray with a Sum of Zero Exists in Java

 

 

Java Program


import java.util.HashSet;

public class SubarrayZeroSum {

    /**
     * Checks if there exists a subarray with a sum of zero.
     *
     * @param arr The input array of integers.
     * @return true if there is a subarray with sum zero, false otherwise.
     */
    public static boolean hasZeroSumSubarray(int[] arr) {
        HashSet set = new HashSet<>();
        int sum = 0;

        for (int num : arr) {
            // Update the sum
            sum += num;

            // Check if the sum is zero or already exists in the set
            if (sum == 0 || set.contains(sum)) {
                return true;
            }

            // Add the sum to the set
            set.add(sum);
        }

        return false;
    }

    public static void main(String[] args) {
        int[] array = {4, 2, -3, 1, 6};
        if (hasZeroSumSubarray(array)) {
            System.out.println("A subarray with a sum of zero exists.");
        } else {
            System.out.println("No subarray with a sum of zero exists.");
        }
    }
}

Program Explanation

The program checks if there is any subarray within the given integer array that sums to zero. It uses a HashSet to store the cumulative sums of the elements as we iterate through the array.

Program Structure

  • Import Statements: The program imports HashSet from the java.util package, which is used to store cumulative sums.
  • Class Definition: The main class is SubarrayZeroSum.
  • Method: hasZeroSumSubarray(int[] arr):
    • Initializes a HashSet to keep track of cumulative sums and a variable to store the current sum.
    • Iterates through each number in the array, updating the cumulative sum.
    • Checks if the cumulative sum is zero or if it has already been encountered (which would indicate a zero sum subarray).
    • If either condition is met, it returns true.
    • If the loop completes without finding such a sum, it returns false.
  • Main Method: The main method initializes an example array and calls hasZeroSumSubarray. It prints the result based on whether a zero-sum subarray exists.

Complexity Analysis

  • Time Complexity: O(n), where n is the number of elements in the array. Each element is processed once.
  • Space Complexity: O(n), in the worst case, if all cumulative sums are distinct and stored in the HashSet.

 

Leave a Reply

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