iharshit009's blog

By iharshit009, 4 years ago, In English

I was doing a problem on Basic Memoization, Longest Common Subsequence( https://leetcode.com/problems/longest-common-subsequence/ )

I wrote a solution:

class Solution {
public:
    int lcs(int i, int j, string text1,string text2, vector<vector<int>>&dp){
        if( i>=text1.size() || j >= text2.size())
            return 0;
        if(dp[i][j] != -1)
            return dp[i][j];
        if(text1[i] == text2[j])
            return dp[i][j] = ( 1+ lcs(i+1 , j +1, text1, text2, dp));
        int left = lcs(i+1, j, text1, text2,dp);
        int right = lcs(i, j +1, text1, text2,dp);
        return dp[i][j] = max(left, right);
    }   
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>>dp(text1.size(), vector<int>(text2.size(), -1));
        return lcs(0,0,text1, text2, dp);
    }
};

Which seems to give TLE on 1/43 test cases, and 42 are passed

On the other side when I submitted this:

class Solution {
public:
    int lcs(int i, int j, string &text1,string &text2, vector<vector<int>>&dp){
        if( i>=text1.size() || j >= text2.size())
            return 0;
        if(dp[i][j] != -1)
            return dp[i][j];
        if(text1[i] == text2[j])
            return dp[i][j] = ( 1+ lcs(i+1 , j +1, text1, text2, dp));
        int left = lcs(i+1, j, text1, text2,dp);
        int right = lcs(i, j +1, text1, text2,dp);
        return dp[i][j] = max(left, right);
    }   
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>>dp(text1.size(), vector<int>(text2.size(), -1));
        return lcs(0,0,text1, text2, dp);
    }
};

It seems to run perfectly in all test cases

The difference in both is of Call by reference and Call by Value Does this create an issue with Time Complexity of an algorithm?

  • Vote: I like it
  • -2
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +32 Vote: I do not like it

if you don't call by reference, the string gets copied every time

»
4 years ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

Since you dont change anything to the string. You can also use const string &s to avoid copy and faster than string &s