Zero Sum - C++ Solution

1. Introduction

The "Zero Sum" problem is a significant concept in algorithm design, particularly useful in understanding array processing and hashing. It involves identifying if a given array contains a contiguous subarray whose sum is zero, a common challenge in computer programming and data analysis.

Problem

Given an array of integers, the task is to determine if the array contains a contiguous subarray with a sum of zero. The problem requires examining various combinations of consecutive elements in the array to find such a subarray, if it exists.

2. Solution Steps

1. Initialize a cumulative sum variable and a hash map to store the cumulative sums encountered.

2. Traverse the array, updating the cumulative sum with each element.

3. Check at each step if the cumulative sum is zero or if it has been encountered before in the hash map.

4. If either condition is met, it indicates the presence of a zero-sum subarray.

5. If the end of the array is reached without finding such a subarray, conclude that no zero-sum subarray exists.

3. Code Program

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

// Function to check for zero-sum subarray in the given array
bool hasZeroSumSubarray(vector<int>& nums) {
    unordered_map<int, bool> sumMap; // Hash map to store the cumulative sums
    int sum = 0; // Cumulative sum of elements
    for (int num : nums) {
        sum += num; // Add current element to cumulative sum
        if (sum == 0 || sumMap.find(sum) != sumMap.end()) {
            return true; // Zero-sum subarray found
        }
        sumMap[sum] = true; // Store the cumulative sum in the hash map
    }
    return false; // Return false if no zero-sum subarray is found
}

int main() {
    vector<int> nums = {3, 4, -7, 3, 1, 3, 1, -4, -2, -2}; // Test array
    cout << (hasZeroSumSubarray(nums) ? "true" : "false") << endl; // Output result
    return 0;
}

Output:

true

Explanation:

The program efficiently determines the existence of a zero-sum subarray using hashing. 

By maintaining a cumulative sum and storing it in a hash map, we can quickly check if a subarray sums to zero. If the cumulative sum becomes zero or if a cumulative sum repeats (implying a zero-sum subarray), the function returns true. 

This method offers an O(n) complexity, making it suitable for large arrays.


Comments