cplusplus
cplusplus

 

 

Program Overview

This program checks if there exists a subarray within a given array of integers that sums to zero.
A subarray is defined as a contiguous portion of an array. The approach utilizes a set to track
the cumulative sum at each index as we iterate through the array. If at any point the cumulative
sum is zero or if the cumulative sum has been seen before, we conclude that a subarray with a sum of zero exists.

C++ Code


#include 
#include 
#include 

using namespace std;

/**
 * Function to check if there exists a subarray with a sum of zero.
 * 
 * @param arr The vector of integers to check.
 * @return true if a zero-sum subarray exists, false otherwise.
 */
bool hasZeroSumSubarray(const vector& arr) {
    unordered_set sumSet; // To store cumulative sums
    int cumulativeSum = 0;      // Initialize cumulative sum

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

        // Check if cumulative sum is zero or if it has been seen before
        if (cumulativeSum == 0 || sumSet.find(cumulativeSum) != sumSet.end()) {
            return true; // Zero sum subarray found
        }

        sumSet.insert(cumulativeSum); // Store the cumulative sum
    }

    return false; // No zero sum subarray found
}

/**
 * Main function to demonstrate the zero sum subarray check.
 */
int main() {
    vector arr = {4, 2, -3, 1, 6}; // Example array

    if (hasZeroSumSubarray(arr)) {
        cout << "A subarray with a sum of zero exists." << endl;
    } else {
        cout << "No subarray with a sum of zero exists." << endl;
    }

    return 0;
}

Program Structure

  1. Includes:The program includes the necessary libraries: iostream for input and output,
    unordered_set for efficient lookup of cumulative sums, and vector
    to manage the dynamic array of integers.
  2. Function hasZeroSumSubarray:This function takes a vector of integers as input and returns a boolean value indicating
    whether a zero-sum subarray exists. It uses an unordered set to keep track of cumulative sums.
  3. Cumulative Sum Calculation:As the program iterates through the array, it maintains a cumulative sum. It checks if
    this sum equals zero or if it has been encountered before in the set. If either condition is
    true, the function returns true, indicating a zero-sum subarray exists.
  4. Main Function:The main function demonstrates the functionality of the hasZeroSumSubarray
    function by providing an example array and printing the result.

Conclusion

This program efficiently checks for a zero-sum subarray using a linear time complexity approach
of O(n) with O(n) space complexity due to the use of an unordered set. This makes it suitable for
large arrays, significantly improving performance over naive O(n²) approaches.

 

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 :)