From 402c65792485ff19f6c615e2c0a385b1f07820bc Mon Sep 17 00:00:00 2001 From: AK271 <56452072+AK271@users.noreply.github.com> Date: Mon, 31 Oct 2022 17:35:18 +0530 Subject: [PATCH] Create zero_sum.cpp --- C++/zero_sum.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/zero_sum.cpp diff --git a/C++/zero_sum.cpp b/C++/zero_sum.cpp new file mode 100644 index 00000000..98c513c5 --- /dev/null +++ b/C++/zero_sum.cpp @@ -0,0 +1,40 @@ +#include +#include +using namespace std; + +void printAllSubarrays(int nums[], int n) +{ + unordered_multimap map; + + map.insert(pair(0, -1)); + + int sum = 0; + + for (int i = 0; i < n; i++) + { + sum += nums[i]; + + if (map.find(sum) != map.end()) + { + auto it = map.find(sum); + + while (it != map.end() && it->first == sum) + { + cout << "Subarray [" << it->second + 1 << "…" << i << "]\n"; + it++; + } + } + + map.insert(pair(sum, i)); + } +} + +int main() +{ + int nums[] = { 3, 4, -7, 3, 1, 3, 1, -4, -2, -2 }; + int n = sizeof(nums)/sizeof(nums[0]); + + printAllSubarrays(nums, n); + + return 0; +}