I was solving this question using dynamic programming. Since I am not much of a fan of using a table/tabulation so I decided to use dictionary. I wrote this.
class Solution:
def findLength(self, arr1: List[int], arr2: List[int]) -> int:
n,m=len(arr1),len(arr2)
i,j=0,0
memo={}
def run(i,j):
key=(i,j)
if i>=n or j>=m:
return 0
if key in memo:
return memo[key]
if arr1[i]==arr2[j]:
memo[key]= 1+run(i+1,j+1)
return memo[key]
memo[key]=max(run(i+1,j),run(i,j+1))
return memo[key]
return run(0,0)
This runs fine on the example testcases such as
[1,2,3,2,1] [3,2,1,4,7] and
[0,0,0,0,0] [0,0,0,0,0]
However it gives a wrong answer on the testcase
[0,1,1,1,1] [1,0,1,0,1]
and gives the result as 3 when the correct output is 2
I cannot figure out what I am missing here.