-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGFG001.cpp
More file actions
68 lines (55 loc) · 1.84 KB
/
GFG001.cpp
File metadata and controls
68 lines (55 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
Given an array of positive and negative numbers, the task is to find if there is a subarray (of size at least one) with 0 sum.
Examples:
Input: {4, 2, -3, 1, 6}
Output: true
Explanation:
There is a subarray with zero sum from index 1 to 3.
Input: {4, 2, 0, 1, 6}
Output: true
Explanation: The third element is zero. A single element is also a sub-array.
Input: {-3, 2, 3, 1, 6}
Output: false
*/
#include <iostream>
#include <unordered_set>
#include <vector>
bool hasZeroSumSubarray(const std::vector<int>& arr) {
std::unordered_set<int> prefixSums;
int currentSum = 0;
for (int num : arr) {
currentSum += num;
if (prefixSums.count(currentSum) || num == 0 || currentSum == 0) { // Check if currentSum already exists
return true;
}
prefixSums.insert(currentSum); // Add currentSum to the set
}
return false;
}
int main() {
std::vector<int> arr1 = {4, 2, -3, 1, 6};
if (hasZeroSumSubarray(arr1)) {
std::cout << "Array 1: Found a subarray with 0 sum" << std::endl;
} else {
std::cout << "Array 1: No subarray with 0 sum" << std::endl;
}
std::vector<int> arr2 = {1, 2, 3, 4, 5};
if (hasZeroSumSubarray(arr2)) {
std::cout << "Array 2: Found a subarray with 0 sum" << std::endl;
} else {
std::cout << "Array 2: No subarray with 0 sum" << std::endl;
}
std::vector<int> arr3 = {-3, 2, 3, 1, 6};
if (hasZeroSumSubarray(arr3)) {
std::cout << "Array 3: Found a subarray with 0 sum" << std::endl;
} else {
std::cout << "Array 3: No subarray with 0 sum" << std::endl;
}
std::vector<int> arr4 = {0};
if (hasZeroSumSubarray(arr4)) {
std::cout << "Array 4: Found a subarray with 0 sum" << std::endl;
} else {
std::cout << "Array 4: No subarray with 0 sum" << std::endl;
}
return 0;
}