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.