How to resolve time limit exceed error from my program

include <iostream>
#include <algorithm>
using namespace std;
 
int main()
{
int n;
cin>>n;
int s[n];
for(int k=0;k<n;k++)
cin>>s[k];
sort(s,s+n);
for(int m=0;m<n;m++
cout<<s[m]<<endl;
return 0;
}

I can’t understand why it is giving time limit exceed and which sorting algorithm does sort(s,s+n) uses and what’s is complexity ?? plz also suggest me some other algo to reduce complexity of my program!!

It’s getting TLE due to slower I/O. Using scanf and printf this solution will get AC. Accepted code

This problem can also be solved using counting sort in O(n) time.
C++ implementation

scanf printf faster than cin cout

STL Sort algorithm

4 Likes

https://www.codechef.com/viewsolution/17473205

Can anyone please explain me why it is giving TIME LIMIT EXCEEDED ?

Post a link to your code instead of pasting the entire code here.

Okk dude!!

Thanks finally get my code accepted!!

Why i getting code accepted in this case
http://www.codechef.com/viewsolution/5503082
and not in that case due to time limit exceeded although these are same

http://www.codechef.com/viewsolution/5503067
Plz help me!!

1 Like

@chaman_amit If you got the answer for your question,then you should mark it as the correct answer,so that it won’t appear in unanswered questions. :slight_smile:

2 Likes

I won’t find any option to mark as correct answer , plz tell me so i ll do that!!

even after using scanf,printf Iam getting time limit exceded, what to do?

1 Like

yes, im getting the same error

why am i getting time limit exceeded in this code

#include <stdio.h>

int main(void) {
int t,n,k;
scanf(“%d”,&t);
while(t–){
scanf(“%d %d”,&n,&k);
while(n>=k){
n=n-k;
}
printf(“%d\n”,n);
}
return 0;
}

Hi, @prince04jn

Thanks for posting a link to the problem, SMOL… https://www.codechef.com/LP1TO201/problems/SMOL

As you know, this problem asks you to find the smallest non-negative integer N that can be made by repeatedly subtracting K.

There’s at least two possible reason why you’re getting TLE error, and both have to do with the problem constraints.

1 \leq T \leq 10^5
1 \leq N \leq 10^9
0 \leq K \leq 10^9

For N=1 and K=0, does your program ever terminate?

And for T=10^5 test cases in which each N=10^9 and each K=1, your program requires 10^5 \cdot 10^9 subtractions. No matter how fast your program is, 10^{14} operations is likely to run out of time.

I hope this is helpful!

–Sbat

Can you tell me how to fix that?
Or can you write any possible solution?

And how is it fixed and then I have not figured out the problem.