MediumStringDynamic Programming

Longest Common Subsequence

LeetCode
1 approach, code in all languages

You are given two strings, text1 and text2. A subsequence keeps the original relative order of characters but may skip any number of them; a common subsequence is one that appears in both strings.

Return the length of the longest subsequence present in both text1 and text2. If no common subsequence exists, return 0.

Example 1

Input: text1 = "abcde", text2 = "ace"

Output: 3

The subsequence "ace" appears in both strings and no longer common subsequence exists, so the answer is 3.

Example 2

Input: text1 = "abc", text2 = "def"

Output: 0

The two strings share no characters, so the longest common subsequence has length 0.

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of lowercase English characters.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now