🔗 LeetCode

Longest Common Subsequence

Medium★ Premiumdynamic programmingAmazonGoogleMicrosoftMetaApple

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.


- For example, "ace" is a subsequence of "abcde".


A **common subsequence** of two strings is a subsequence that is common to both strings.

Examples

Input:text1 = "abcde", text2 = "ace"
Output:3
Explanation:The longest common subsequence is "ace" and its length is 3.
Input:text1 = "abc", text2 = "abc"
Output:3
Explanation:The longest common subsequence is "abc" and its length is 3.
Input:text1 = "abc", text2 = "def"
Output:0
Explanation:There is no such common subsequence, so the result is 0.
Input:text1 = "abc", text2 = "ac"
Output:2
Explanation:The longest common subsequence is "ac" with length 2 (matches the step-by-step dry-run visualization).

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.

💡 Hints

Hint 1

Use a 2D dynamic programming grid where dp[i][j] stores the length of the LCS for text1[0..i-1] and text2[0..j-1].

Hint 2

If text1[i-1] matches text2[j-1], take the diagonal value plus one: dp[i][j] = dp[i-1][j-1] + 1.

Hint 3

If characters do not match, take the maximum of the top cell and left cell: dp[i][j] = max(dp[i-1][j], dp[i][j-1]).

Algorithm Complexity

Official asymptotic Big-O runtime and auxiliary memory analysis

Quadratic
Algorithmic Approach

2D tabular dynamic programming. Build an (M+1) x (N+1) grid. If characters match, take dp[i-1][j-1] + 1. Otherwise, take max(dp[i-1][j], dp[i][j-1]).

Time ComplexityO(M * N)
Why:

Fills a 2D dynamic programming grid of size (M + 1) × (N + 1) where each cell transition computes in O(1).

Space ComplexityO(M * N)
Why:

The 2D table requires (M + 1) × (N + 1) integer storage cells.

Big-O Growth CurveQuadratic (O(N²))
Execution time grows quadratically with nested iterations over the input.

🌍 Real-World Use Cases

Git / GitHubFile Diffing & Merge Conflict Resolution

Computing line-by-line diffs between committed file versions using the Myers diff algorithm based on Longest Common Subsequence.

★ Premium Challenge

Longest Common Subsequence is classified as a premium problem.

Client-Side Architecture Preview (Phase 3 Sprint 3)
This gating is an honest client-side architecture preview. True secure server entitlements, user database roles, and payment verification will be introduced in Phase 4 with the PostgreSQL backend. There is no fake checkout or simulated payment processing.
Difficulty: MediumPattern: dynamic-programmingCompanies: Amazon, Google, Microsoft