While solving problems on any online judge sometimes it might get Time Limit Exceeded. Below are some of the ways to optimize the code:
- Minimize the use of loops inside loops i.e., Nested Loops: For Example:
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.
- Don’t prefer a long chain of if-else, instead prefer to use Switch Statements: For Example:
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.
- Instead of using “i = i + 1“, prefer using “++i”, and instead of “i = i + 3“, use “i +=3“.
- 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++;
- 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 advisable to use StringBuilder (in java) instead of “+” operator for concatenation.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!