Skip to main content

Longest Common Subsequence Length

medium
Dynamic ProgrammingStringDp 2d
Asked atGoogleAmazonMicrosoftMetaApple

Problem Description

Given two strings `textA` and `textB`, return the length of their **longest common subsequence** (LCS).

A **subsequence** is a sequence derived from a string by deleting zero or more characters without changing the relative order of the remaining characters. A **common subsequence** is one that is a subsequence of both strings.

If there is no common subsequence, return `0`.

**Example 1:**
```
Input: textA = "carpet", textB = "apart"
Output: 4
Explanation: "aprt" is a common subsequence of length 4.
```

**Example 2:**
```
Input: textA = "flight", textB = "fright"
Output: 5
Explanation: "fIght" → "fight" is a common subsequence of length 5.
```

Constraints

  • 1 <= textA.length, textB.length <= 1000
  • textA and textB consist of lowercase English letters only

Follow-up

Can you reconstruct and return the actual longest common subsequence string, not just its length?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.

CodeBrainery

A technical blogging platform for developers and engineers to share knowledge and connect.

Connect

© 2026 Kodetra Technologies Pvt. Ltd. All rights reserved. CodeBrainery is a product of Kodetra Technologies Pvt. Ltd.