Skip to main content

Sub array with given Sum

Task: Find the continuous sub-array, from given an array of size N non negative integers, which sum is equal to given S.

Example:
Input:
1
5 12
1 2 3 7 5
Output:
2 4 // starting and ending positions of sub-array.

Here is the code:
Program in C++:

  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4.  {
  5. int t;
  6. cin>>t;
  7. while(t--)
  8. {
  9.     int n,s;
  10.     cin>>n>>s;
  11.     int a[n];
  12.     for(int i=0;i<n;i++)
  13.     {
  14.         cin>>a[i];
  15.     }
  16.     // Implementaion of Logic
  17.     int sas=0,i=0,c=0;
  18.     for(int j=0;j<n;j++)
  19.     {
  20.         if(sas+a[j]<=s)
  21.         {
  22.             sas+=a[j];
  23.         }
  24.         else
  25.         {
  26.             sas+=a[j];
  27.             while(sas>s)
  28.             {
  29.                 sas-=a[i];
  30.                 i++;
  31.             }
  32.         }
  33.         if(sas==s)
  34.         {
  35.             cout<<i+1<<" "<<j+1<<endl;
  36.             c=1;
  37.             break;
  38.         }
  39.     }
  40.     if(c==0) cout<<-1<<endl;
  41. }
  42. return 0;
  43. }


Here is the Video: