Skip to content

Commit 7239b65

Browse files
authored
Merge pull request ashutosh97#79 from Piyush-Karira/master
Added Zero Sum SubArray simple and effective solution
2 parents 3e6ffc4 + e2450cc commit 7239b65

File tree

4 files changed

+96
-0
lines changed

4 files changed

+96
-0
lines changed

Merging_Two_Sorted_Array/question.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Given two sorted arrays arr1[] and arr2[] in non-decreasing order with size n and m. The task is to merge the two sorted arrays into one sorted array (in non-decreasing order)

Merging_Two_Sorted_Array/solution.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
int main()
4+
{
5+
int t;
6+
cin>>t;
7+
while(t--)
8+
{
9+
int x,y;
10+
cin>>x>>y;
11+
long a[x+1],b[y+1];
12+
for(int i=0;i<x;i++)
13+
cin>>a[i];
14+
for(int i=0;i<y;i++)
15+
cin>>b[i];
16+
17+
int i=0,j=0;
18+
vector<long> vec;
19+
while(i<x&&j<y)
20+
{
21+
if(a[i]<b[j])
22+
{
23+
vec.push_back(a[i]);
24+
i++;
25+
}
26+
else if(a[i]>b[j])
27+
{
28+
vec.push_back(b[j]);
29+
j++;
30+
}
31+
else if(a[i]==b[j])
32+
{
33+
vec.push_back(a[i]);
34+
vec.push_back(b[j]);
35+
i++;
36+
j++;
37+
}
38+
}
39+
while(i<x)
40+
{
41+
vec.push_back(a[i]);
42+
i++;
43+
}
44+
while(j<y){
45+
vec.push_back(b[j]);
46+
j++;
47+
}
48+
for(int i=0;i<vec.size();i++)
49+
cout<<vec[i]<<" ";
50+
51+
cout<<endl;
52+
}
53+
return 0;
54+
}

Zero_Sum_SubArray/question.txt

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Given an Array of size N, identify whether there exists a subarray with zero sum?
2+
3+
Conditions: -10^6<=N<=10^6
4+
Time limit is 1.0 sec

Zero_Sum_SubArray/solution.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* C++ Solution */
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
/*Function to check whether zero sum subarray exists or not*/
7+
bool hasZeroSum(int arr[], int N)
8+
{
9+
set<int> st;
10+
int sum=0;
11+
for(int i=0;i<N;i++)
12+
{
13+
sum+=arr[i];
14+
/*if Set contains a sum already,
15+
that means zero sum subArray exists*/
16+
if(st.find(sum)!=st.end()||sum==0)
17+
return true;
18+
19+
st.insert(sum);
20+
}
21+
return false;
22+
}
23+
24+
int main() {
25+
int N;
26+
cin>>N;
27+
int arr[N+1];
28+
29+
//Array input
30+
for(int i=0;i<N;i++)
31+
cin>>arr[i];
32+
33+
34+
bool ans = hasZeroSum(arr,N);
35+
cout<<ans;
36+
return 0;
37+
}

0 commit comments

Comments
 (0)