Skip to the solution
MediumDSA15 min read

How do you find the longest common subsequence?

363 views

The problem

Question presented to candidate: "Given two strings, return the length of their longest common subsequence โ€” characters in the same order, but not necessarily next to each other. Then show me how you would get the subsequence itself. Please code it in Python."

What a strong answer should cover:

  • The state dp[i][j] = LCS length of the first i characters of one string and the first j of the other, with row 0 and column 0 meaning the empty prefix.
  • The recurrence: equal last characters โ†’ dp[i-1][j-1] + 1; different โ†’ max(dp[i-1][j], dp[i][j-1]); and why the order of filling makes every input ready.
  • O(mยทn) time and space, and the two-row version in O(min(m, n)) space when only the length is needed.
  • Rebuilding the string by walking back from dp[m][n], and noting that ties mean the LCS is not unique.
  • Python details: building rows with a list comprehension (not [[0] * n] * m, which aliases one row), and that a memoized recursive version hits the default recursion limit of 1000 on long strings.

Clarifying questions expected:

  • Do you need the length only, or the subsequence string as well?
  • Subsequence (gaps allowed) or substring (contiguous)?
  • How long can the strings get?

Code / implementation expected: Yes โ€” a bottom-up table in Python returning the length, plus a walk back that returns one LCS string.

  • dp
  • lcs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

15 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonLCS table, length and one LCS string on six pairs
PythonNaive recursion vs memo vs table vs two rows

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 98 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find a peak element in an array?

Continue