Problem
1143. Longest Common Subsequence
The longest common subsequence problem is a classic computer science problem, the basis of data comparison programs such as the diff utility, and has applications in computational linguistics and bioinformatics. It is also widely used by revision control systems such as Git for reconciling multiple changes made to a revision-controlled collection of files.
For the general case of an arbitrary number of input sequences, the problem is NP-hard. When the number of sequences is constant, the problem is solvable in polynomial time by dynamic programming.
The LCS problem has an optimal substructure: the problem can be broken down into smaller, simpler subproblems, which can in turn be broken down into simpler subproblems, and so on, until, finally, the solution becomes trivial. LCS in particular has overlapping subproblems: the solutions to high-level subproblems often reuse solutions to lower level subproblems. Problems with these two properties are amenable to dynamic programming approaches, in which subproblem solutions are memoized, that is, the solutions of subproblems are saved for reuse.
Java
Hunt–Szymanski algorithm
Translation of © Hunt-Szymanski Algorithm(Match-List, 1977)
1 | class Solution { |
Submission Detail
- 43 / 43 test cases passed.
- Runtime: 12 ms, faster than 32.13% of Java online submissions for Longest Common Subsequence.
- Memory Usage: 39.2 MB, less than 92.10% of Java online submissions for Longest Common Subsequence.
Dynamic Programming
bottom-up approach
Oftentimes I found Wikipedia is helpful when doing leetcode algorithm problems.
1 | class Solution { |
Submission Detail
- 43 / 43 test cases passed.
- Runtime: 18 ms, faster than 17.54% of Java online submissions for Longest Common Subsequence.
- Memory Usage: 42.8 MB, less than 51.59% of Java online submissions for Longest Common Subsequence.
top-down approach (momoized version)
© https://www.techiedelight.com/longest-common-subsequence/
1 | class Solution { |
Submission Detail
- 43 / 43 test cases passed.
- Runtime: 295 ms, faster than 5.04% of Java online submissions for Longest Common Subsequence.
- Memory Usage: 167 MB, less than 5.04% of Java online submissions for Longest Common Subsequence.
javascript
Dynamic Programming
1 | /** |
Submission Detail
- 43 / 43 test cases passed.
- Runtime: 116 ms, faster than 60.08% of JavaScript online submissions for Longest Common Subsequence.
- Memory Usage: 53.4 MB, less than 22.63% of JavaScript online submissions for Longest Common Subsequence.