Lower Bound and Upper Bound

Time Limit Exceeded

#include
using namespace std;
int a[100];
int lower(int s,int e,int q,int ans)
{
while(s<=e)
{
int m;
m=(s+e)/2;
if(a[m]>q)
{
s=s;
e=m-1;
lower(s,e,q,ans);
}
else if(a[m]<q)
{
s=m+1;
e=e;
lower(s,e,q,ans);
}
else if(a[m]==q)
{
ans=m;
s=s;
e=m-1;
lower(s,e,m,ans);
}
}
return ans;

}
int upper(int s,int e,int q,int ans)
{
while(s<=e)
{
int m;
m=(s+e)/2;
if(a[m]>q)
{
s=s;
e=m-1;
upper(s,e,q,ans);
}
else if(a[m]<q)
{
s=m+1;
e=e;
upper(s,e,q,ans);
}
else if(a[m]==q)
{
ans=m;
s=s;
e=m+1;
upper(s,e,m,ans);
}
}
return ans;

}
int main() {
int i,q,q1;
int n;
cin>>n;
int s,e;
for(i=0;i<n;i++)
{
cin>>a[i];
}
cin>>q;
for(i=0;i<q;i++)
{
cin>>q1;
s=0,e=n-1;
cout<<lower(s,e,q1,-1);
cout<<" “<<upper(s,e,q1,-1);
cout<<”\n";
}
return 0;
}

paste code on coding blocks IDE and share link here
mention problem link

https://ide.codingblocks.com/s/59438

https://hack.codingblocks.com/contests/c/670/675

Hey you are mixing both iterative and recursive approach which increase the complexity.
Either use only while loop
line no 6
while(s<=e) and dont use lower(s,e,q,ans); at line 14,20,27
or
use if(s<=e) and use lower(s,e,q,ans);

Your while loop is taking it TLE.
You are getting it or I need to explain in detail?

Updated Code https://ide.codingblocks.com/s/59438

Still getting the time Limit Error.

Line 37:
Use s=m+1
as starting point will be changed

Oh its my mistake.
Thank you Bhaiya.

1 Like