InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Longest Common Subsequence

medium Original ↗ 00:00

Problem

Given two strings text1 and text2, return the length of their longest common subsequence (LCS). A subsequence keeps characters in their original relative order but may skip any number of them (it need not be contiguous). A common subsequence is one that appears in both strings.

If there is no common subsequence, return 0.

Examples

  • text1 = "abcde", text2 = "ace"3"ace" is a subsequence of both.
  • text1 = "abc", text2 = "abc"3 — identical strings; the whole string is the LCS.
  • text1 = "abc", text2 = "def"0 — no shared characters at all.

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • Both strings consist of lowercase English letters.

Lengths up to 1000 each mean the expected solution is O(m × n) — up to a million cells.

Think about it first

Hint 1 Compare the last characters. If they are equal, that pair can be the tail of the LCS — count it and recurse on both shorter prefixes. If they differ, at least one of those two characters is not in the LCS, so try dropping each and keep the better result.
Hint 2 The subproblem is "LCS length of `text1`'s first `i` characters and `text2`'s first `j` characters." Two prefix lengths → a 2-D table `dp[i][j]`.
Hint 3 If `text1[i-1] == text2[j-1]`: `dp[i][j] = 1 + dp[i-1][j-1]`. Otherwise `dp[i][j] = max(dp[i-1][j], dp[i][j-1])`. The row and column for an empty prefix are all zeros.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug