Skip to content
Related Articles

Related Articles

Improve Article

Ways to remove TLE

  • Difficulty Level : Medium
  • Last Updated : 14 Sep, 2021
Geek Week

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++;
  • Also use of pointer should be avoided, where can be avoided. 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.
  • Use StringBuilder or StringBuffer class for concatenation instead of ‘”+” operator
        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 adviceable to use StringBuilder (in java) instead of “+” operator for concatenation.

GeeksforGeeks LIVE courses

My Personal Notes arrow_drop_up
Recommended Articles
Page :