WHY I am getting a TLE?

135 Views Asked by At

PROBLEM: I am getting a TLE in this LEETCODE problem of finding the longest common subsequence. with 42/45 test cases being passed. please help. YOU CAN COPY PASTE BELOW CODE ON LEETCODE 1143 PROBLEM and help if possible:

//solve(i,j)-->represents length of LCS till index i and j in string text1 and text2 respectively.

int solve(string text1, string text2,int i,int j,int dp[1001][1001]){
    //base case
    if(i<0||j<0){
         return 0 ;
    }

    if(dp[i][j]!=-1) {
        return dp[i][j];
    }
    else{
        if(text1[i]==text2[j]){
            return dp[i][j] = 1+ solve(text1,text2,i-1,j-1,dp) ;                                
        }
    
        else{
            return dp[i][j] = max(solve(text1,text2,i,j-1,dp),solve(text1,text2,i-1,j,dp));
        }
     }
}

int longestCommonSubsequence(string text1, string text2) {
    int m=text1.size();
    int n=text2.size();
    
    int dp[1001][1001];
    memset(dp,-1,sizeof(dp));
    
    return solve(text1,text2,m-1,n-1,dp);
}
1

There are 1 best solutions below

2
Dialecticus On

Reason for TLE is that solve recursion is not efficient. Recursion is happening twice (here: max(solve(text1,text2,i,j-1,dp),solve(text1,text2,i-1,j,dp))). Try to find a more efficient algorithm.

Instead of recursion I would just iterate through the matrix, only not by row or by column, but by diagonal.

Minor improvement would be to pass strings by reference (so string& instead of just string).