Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Dynamic Programming High frequency Solution Available Practice Mode

Longest Common Subsequence LeetCode Solution

Tags: #String #DP

Approach Summary

dp[i][j] = LCS of first i chars of s1 and first j chars of s2. If match: dp[i-1][j-1]+1. Else: max(dp[i-1][j], dp[i][j-1]).

Practice Mode 2 Progressive Approaches

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Dynamic Programming Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Dynamic Programming pattern.

Framework: Dynamic Programming • Interview Prep: Tested at FAANG • Explore all Dynamic Programming problems & invariants →

How to Recognize This Pattern

  • LCS of two sequences
  • 2D DP table

Complexity Analysis

Time Complexity

O(m × n)

Space Complexity

O(m × n)

Tags

String DP

Frequently Asked Questions

What is the optimal time and space complexity for Longest Common Subsequence?
The optimal solution for Longest Common Subsequence achieves O(m × n) runtime complexity and requires O(m × n) auxiliary space. Time complexity is O(m * n) where m and n are string lengths because every cell in the m x n grid is evaluated in O(1) time. Space complexity is O(n) using rolling 1D arrays.
How do I identify that Longest Common Subsequence requires the Dynamic Programming pattern?
In technical interviews, look for key problem signals: LCS of two sequences; 2D DP table. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Dynamic Programming strategy.
What critical edge cases must be handled in Longest Common Subsequence?
Essential edge cases to verify include: No common characters (e.g. "abc" and "def"; returns 0); Identical strings (returns string length); One string is an exact subsequence of the other (e.g. "abc" and "aebdc"; returns 3); Strings with unequal lengths (e.g. length 1 vs 1000). Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Longest Common Subsequence?
Longest Common Subsequence is a Medium-difficulty question tagged with high recurrence. It is actively asked in technical screening and onsite interview loops at Google, Amazon, Bloomberg.
Buy me a coffee
Daily Practice
0/0