Skip to main content
Back to problems
Leetcode
Medium
Dynamic Programming
DP on Strings
Strings
Google
Amazon
Microsoft
Longest Common Subsequence

Find the length of the longest subsequence that appears in both strings.

Acceptance 0%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

Given two strings text1 and text2, determine the length of their longest common subsequence (LCS).

A subsequence is formed by deleting zero or more characters without changing the order of the remaining characters. The characters of the subsequence do not need to be contiguous.

Your task is to compute the maximum possible length of a string that is a subsequence of both text1 and text2.

Notes

  • The subsequence may be empty.
  • You only need to return the length, not the subsequence itself.

Input Format

  • Two strings text1 and text2.
  • The strings consist of lowercase English letters in the standard LeetCode version.

Output Format

  • Return a single integer: the length of the longest common subsequence of the two strings.

Constraints

  • 0text1,text210000 \le |text1|, |text2| \le 1000
  • Characters are lowercase English letters in the standard version.
  • A valid solution should run in O(nm)O(nm) time for strings of lengths nn and mm.
Examples
Sample cases returned by the problem API.

Example 1

Input

text1 = "abcde", text2 = "ace"

Output

3

Explanation

The longest common subsequence is "ace", which has length 3.

Example 2

Input

text1 = "abc", text2 = "abc"

Output

3

Explanation

The entire string is common, so the LCS length is 3.

Show 1 more example

Example 3

Input

text1 = "abc", text2 = "def"

Output

0

Explanation

The strings share no common subsequence except the empty one.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.