LeetCode: Longest Common Subsequence Solution
Classic dynamic programming problemApproach: Memoized Recursion
Let recursion(m, n)
return length of the longest common subsequence of text1.substring(0, m)
and text2.substring(0, n)
. m
and n
here refer to length, not 0-based index
- if
m === 0 || n === 0
,recursion(m, n)
returns0
- if
text[m - 1] === text[n - 1]
,recursion(m, n)
returns1 + recursion(m - 1, n - 1)
- else
recursion(m, n)
returnsmax(recursion(m, n - 1), recursion(m - 1, n))
Implementation
1var longestCommonSubsequence = function (text1, text2) {2 const memo = Array.from({ length: text1.length + 1 }, _ =>3 Array(text2.length + 1).fill(null)4 )56 const recursion = (m, n) => {7 if (memo[m][n] !== null) return memo[m][n]89 if (m === 0 || n === 0) return (memo[m][n] = 0)1011 if (text1[m - 1] === text2[n - 1])12 return (memo[m][n] = 1 + recursion(m - 1, n - 1))1314 return (memo[m][n] = Math.max(recursion(m, n - 1), recursion(m - 1, n)))15 }1617 return recursion(text1.length, text2.length)18}
References
Comments
Loading comments...
Tags
leetcode
recursion
dynamic programming
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.