Time Complexity

Can anyone please help me regarding time complexity, I knew basic of them n(O) and all but how does this online compiler really decides the time complexity of code, please explain in details like whether it depends on input, output, datatype, loops and all. I am using c++.

For example consider this two code.
//////////////////////////////////////////////////////////////////////
Code 1.

#include <bits/stdc++.h>
using namespace std;

int main()
{
int t;
cin>>t;
for(int i=0;i<t;i++)
{
int n;
cin>>n;
long long arr[n];
for(int j=0;j<n;j++)
{
cin>>arr[j];
}
sort(arr,arr+n);
long long min1=arr[0];
long long diff=0;
for(int j=1;j<n;j++)
{
diff=diff+(arr[j]-min1);
}
cout<<diff<<endl;
diff=0;
}
}
//////////////////////////////////////////////////////
Code 2.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t–)
{
int n,count=0;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr, arr+n);
for(int i=1;i<n;i++)
count = count + (arr[i] - arr[0]);
cout<<count<<endl;
}
return 0;
}
//////////////////////////////////////////////////
Here the first code runs fine but second code throws time limit exceed RTE.
Also if shift the input in while loop of test case than it works fine
like this:
while(t-- && cin>>n)
{
//code
}
why so…?
Please help me.

Thank You

Both of the codes are working fine. i didn’t get any RTE when submitted. And time complexity of code depends on operations we are performing. For ex. you are using sort() which takes time of O(NlogN) for each testcase. Similary you can guess the upper time limit require for code base on operations perform. If compiler doesn’t allow that much time it will throw an error RTE or TLE . then you need to either optimized your algorithm or check whether it’s going in infinite loop.

Also from next time plz write your code in preformatted text or any other online ide. It becomes unreadable when you simply copy paste your code.
If you don’t know read this - https://discuss.codechef.com/t/tutorial-color-format-the-code/36585

1 Like