Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
"ace" is a subsequence of "abcde".A common subsequence of two strings is a subsequence that is common to both strings.
Example 1:
Input: text1 = "abcde", text2 = "ace" Output: 3 Explanation: The longest common subsequence is "ace" and its length is 3.
Example 2:
Input: text1 = "abc", text2 = "abc" Output: 3 Explanation: The longest common subsequence is "abc" and its length is 3.
Example 3:
Input: text1 = "abc", text2 = "def" Output: 0 Explanation: There is no such common subsequence, so the result is 0.
Constraints:
1 <= text1.length, text2.length <= 1000text1 and text2 consist of only lowercase English characters.Why this is a 2D Dynamic Programming problem
2D DP stores answers in a 2D table dp[i][j], where i and j typically represent two independent dimensions — like two strings, a grid position, or (item, remaining-capacity) in knapsack. The final answer is usually dp[m][n] built from smaller sub-tables.
Draw the 2D table first. Label the axes. Then figure out what dp[i][j] means and which neighboring cells it depends on.
Picture an edit-distance problem: to transform "cat" into "car" you can insert, delete, or replace. Each decision combines the results of transforming smaller prefixes. The 2D table captures every possible prefix-pair in one grid — and each cell is filled in O(1) using the three cells above-left, above, and left.
From brute force to optimal — understand every step of the journey
The hardest part is defining what dp[i][j] represents. Write it as an English sentence before touching code. For string problems, i and j almost always represent prefix lengths (not indices). For grid problems, dp[i][j] represents the answer reaching cell (i, j). Once you have the definition, ask: "what choice do I make at (i, j), and what prior state does each choice depend on?"