Data Structures & Algorithms Dynamic Programming — 2D
💡
Exercise 131

Longest Common Subsequence 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Find the longest common subsequence of two strings. Elements don't need to be contiguous.

text1 = "abcde" text2 = "ace" # LCS = "ace" → length 3

2D DP: if chars match, dp[i][j] = dp[i-1][j-1] + 1. Otherwise, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find length of longest common subsequence.
Create 2D dp of (m+1)×(n+1). If text1[i-1]==text2[j-1], diagonal+1. Else, max of top and left.
🧪 Test Cases
Input
longestCommonSubsequence('abcde', 'ace')
Expected
3
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.