Open In App

Ways to remove TLE

While solving problems on any online judge sometimes it might get Time Limit Exceeded. Below are some of the ways to optimize the code:

     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.



if(condition 1)
{

}
else
{
if(condition 2)
{

}
else
{

}
}

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 the below code:

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.



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++;
        1.Using "+" operator
String x="";
char c='a';
for(int i=0;i<10000;i++)
x+=c;

2.Using StringBulider/StringBuffer Class
StringBuilder sb=new StringBuilder("");
char c='a';
for(int i=0;i<10000;i++)
sb.append(c);
String x=sb.toString();

Both of them does the same work(making a string of 10000 copies of ‘a’ character). But the 2nd option takes 10 times less time than the 1st one.

So,it is always advisable to use StringBuilder (in java) instead of “+” operator for concatenation.

Article Tags :