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
- Includes:The program includes the necessary libraries:
iostream
for input and output,
unordered_set
for efficient lookup of cumulative sums, andvector
to manage the dynamic array of integers. - 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. - 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. - Main Function:The
main
function demonstrates the functionality of thehasZeroSumSubarray
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.