0

I was trying to solve a leetcode problem when I came across this error. This gives me the correct answer:

    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        lookup = [[0]*(len(text2)+1) for x in range(len(text1)+1)]
        for j in range(len(text2)-1, -1, -1):
            for i in range(len(text1)-1, -1, -1):
                if text1[i] == text2[j]:
                    lookup[i][j] = 1+lookup[i+1][j+1]
                else:
                    lookup[i][j] = max(lookup[i+1][j], lookup[i][j+1])
        return lookup[0][0]

However, this doesn't give me the correct answer:

def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        lookup = [[0]*(len(text2)+1)]*(len(text1)+1)
        for j in range(len(text2)-1, -1, -1):
            for i in range(len(text1)-1, -1, -1):
                if text1[i] == text2[j]:
                    lookup[i][j] = 1+lookup[i+1][j+1]
                else:
                    lookup[i][j] = max(lookup[i+1][j], lookup[i][j+1])
        return lookup[0][0]

I'm not too sure why this is the case. When I initialize my lookup table, they are both equivalent to each other. Can someone tell me why? Thank you!

0 Answers0