15% off all plans & roadmaps Use code
See plansLeetCode 1143 · Solution & editorial
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
Longest Common Subsequence is a Dynamic Programming (DP) Patterns problem, in the 2D Array (Longest Common Subsequence - LCS) subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
Find longest common subsequence between two strings using 2D DP.
The reference solution runs in O(m * n) time and O(min(m, n)) space.
Longest Common Subsequence has been reported in interviews at Amazon, eBay, Google, Microsoft.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Longest Common Subsequence is a Dynamic Programming (DP) Patterns problem, in the 2D Array (Longest Common Subsequence - LCS) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.