Java
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)