In this article, we are going to see some useful tips to overcome the time limit exceed error. The most common reason that you would get a Time Limit Exceeded is that your program is too slow.
All the competitive programmers must have faced this problem. and many programmers always argue that the problems in Competitive Programming always end up with TLE(Time Limit Exceed). The main problem with this error is that it will not allow you to know that your solution would reach to correct solution or not!
So let's see some of the ways to optimize the code
- Don’t prefer a long chain of if-else, instead prefer to use Switch Statements.
if(condition 1)
{
// code
}
else
{
if(condition 2)
{
// code
}
else
{
// code
}
}
Suppose there is another condition 3, then the flow of code is to first check condition 1, then condition 2 then it will reach condition 3. Therefore, it requires 3 number of operation.
The idea is to use another logic using switch cases understand by the example below:
switch (c)
{
// Condition 1
case 1:
break;
// Condition 2
case 2 :
break;
// And so on
}
In the switch case, the compiler will directly go to the condition and execute them without executing the other conditions.
Instead of using “i = i + 1“, prefer using “++i”, and instead of “i = i + 7“, use “i +=7“.
Better prefer pre-increment or pre-decrement over post-increment and post-decrement until and unless it is required. For Example:
int i = 3;
// It will increment in the same step
++i;
// It will increment in the next step
// so it will take more time
i++;
- Do not use pointer unnecessary. A pointer points to the address of a variable, that address will be further used to access the variable. So try to directly access the variable as they can be directly used and hence time can be reduced.
2. Minimize the use of loops inside loops i.e., Nested Loops.
for(i = 0 ; i < n ; i++)
{
for(j = 0 ; j < n ; j++)
{
// Your Code
}
}
The above code will perform N*N iterations and will take more time, to avoid this, the idea is to think of an approach that minimizes the use of loops inside loops.
3. Change methods of Input-Output.
You must choose proper input-output functions and data structure that would help you in optimization.
In C++, do not use cin/cout – use scanf and printf instead.
In Java, do not use a Scanner – use a BufferedReader instead.
4. Optimize your Algorithm
If nothing works after all this, then you should try changing the algorithm or the approach you are using to solve your problem. Generally, the internal test cases are designed in such a way that you will be able to clear all of them only if you choose the best possible algorithm.
Ultimately, with experience, you’ll surely come to know what to do and what not to avoid TLEs. The more you code the more you get to know about how to compete for TLE.
So this is it for today!.
I hope you liked it!. Let's catch up in the next articles and Stay tuned.
If you liked it, Please Support Me