Explain LCS.
Skip to solutionKEEP THE
mediumDSA
How do you find the longest common subsequence?
363 views
01
Understand the problem
dplcs
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Use a 2D DP table where dp[i][j] is the LCS length of prefixes. If characters match, dp[i][j] = dp[i-1][j-1]+1; else the max of dropping one character from either string. O(m×n).
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
LCS length (2-D DP)
Run Playgrounddef lcs(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[m][n]
# --- demo ---
print(lcs("ABCBDAB", "BDCAB")) # 4 (e.g. "BCAB")05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 78 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.